htmx

Is there a way to make hx-trigger dependent on the selected value?


I have a box with multiple options. For certain options, I need to display another select, but not for the other ones.

<select>
  <option value="scala">Scala</option>
  <option value="java">Java</option>
</select>

Is there some way in hx-trigger to only perform the trigger based on the value of the selected option?


Solution

  • Of course, the real answer is to use the htmx:beforeRequest event to cancel the request:

    <select name="choice"
            hx-get="/example"
            hx-on::before-request="if (event.detail.elt.value == 'Or')
                                       event.preventDefault();">
        <option></option>
        <option>Something</option>
        <option>Or</option>
        <option>Other</option>
    </select>
    

    Or perhaps more declaratively:

    <select name="choice"
            hx-get="/example"
            hx-on::before-request="if (event.detail.elt.selectedOptions[0].dataset.more == null)
                                       event.preventDefault();">
        <option></option>
        <option data-more>Something</option>
        <option>Or</option>
        <option data-more>Other</option>
    </select>