Skip to content
Advertisement

AlpineJS: which x-on directive to use inside tag? @click does not seem to work on tag

I’d like to trigger an action when a specific option is selected in select tag. @click works on every other tags, but when it doesn’t seem to work on option. Is there a directive like @selected where I can trigger an action when an option is selected?

<html>
  <head>
    <script defer src="https://unpkg.com/alpinejs@3.3.4/dist/cdn.min.js"></script>
  </head>

  <body>

    <div x-data="{}">

        <!-- this does NOT work -->
        <select>
            <option @click="alert('option 1');">option 1</option>
            <option @click="alert('option 2');">option 2</option>
            <option @click="alert('option 3');">option 3</option>
        </select>

        <!-- this works -->
        <button @click="alert('button clicked');">Click</button>

    </div>

  </body>
</html>

Advertisement

Answer

You can’t attach events to <option> tags, but you can attach a change event to the <select> tag and use the value of the selected option.

<select x-on:change="alert($el.value)">
    <option>option 1</option>
    <option>option 2</option>
    <option>option 3</option>
</select>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement