I want to handle click to option in select input.
how alpine can help me.
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-modelattribute 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?
Most helpful comment
As far as i know, you can't use
@clickevent onoption. You can only consider to usechangeevent on theselectitself. You could useclickevent on theselectbut i don't think that will be the use case. So the right way to go is use the@changeevent on theselect.if you need to check the
selectedvalue and do something with it, you can use$event.target.valueto 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