Alpine: select input

Created on 17 Apr 2020  路  5Comments  路  Source: alpinejs/alpine

I want to handle click to option in select input.
how alpine can help me.

question

Most helpful comment

As far as i know, you can't use @click event on option. You can only consider to use change event on theselect itself. You could use click event on the select but i don't think that will be the use case. So the right way to go is use the @change event on the select.

if you need to check the selected value and do something with it, you can use $event.target.value to grab the value of it and maybe do a check like $event.target.value == 1 ? foo = 'bar' : foo = 'baz', you can do like so.

here is a sample for your reference

<div x-data="{foo :'not selected'}">
  <select @change="foo = $event.target.value">
    <option x-bind:value="1">option 1</option>
    <option x-bind:value="2">option 2</option>
    <option x-bind:value="3">option 3</option>
  </select>
  <span x-text="'option '+ foo"></span>
</div>

All 5 comments

You can use x-model on the select or bind to its change event using x-on:change or @change. Note that "option click" is the same as "select change".

I've got a select example at https://alpinejs.codewithhugo.com/select-and-access/

As far as i know, you can't use @click event on option. You can only consider to use change event on theselect itself. You could use click event on the select but i don't think that will be the use case. So the right way to go is use the @change event on the select.

if you need to check the selected value and do something with it, you can use $event.target.value to grab the value of it and maybe do a check like $event.target.value == 1 ? foo = 'bar' : foo = 'baz', you can do like so.

here is a sample for your reference

<div x-data="{foo :'not selected'}">
  <select @change="foo = $event.target.value">
    <option x-bind:value="1">option 1</option>
    <option x-bind:value="2">option 2</option>
    <option x-bind:value="3">option 3</option>
  </select>
  <span x-text="'option '+ foo"></span>
</div>

You might also consider using a watcher alongside the x-model attribute if you need to observe the change from elsewhere in the component :)

Closing this for now since there's a few suggestions, feel free to reopen or comment if you're having specific issues binding to a select.

You might also consider using a watcher alongside the x-model attribute if you need to observe the change from elsewhere in the component :)

Hi @ryangjchandler, thanks for your comment on this post. Would you provide a short example of how to use the x-model attribute to observe a change with a select element?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

piotrpog picture piotrpog  路  3Comments

haipham picture haipham  路  4Comments

zaydek picture zaydek  路  3Comments

adinata-id picture adinata-id  路  4Comments

dkuku picture dkuku  路  5Comments