alpine.js – Call function through livewire with the value of a custom data-attribute as a parameter – Code Utility

[

I have a select input which, using livewire, calls a function whenever the selection changes. According to the documentation you can use $event.target.value to get to the selected value, however I want to send a different attribute value (myvalue) to my function.

<!-- this doesnt work -->

<select wire:onchange="myfunction($event.target.dataset.myvalue)">
    <option value="1" data-myvalue="12345">
</select>

I got it working using Alpine.js but it seems odd that I need another framework to do so.

<!-- this does work, but requires alpine.js -->

<select x-data='{}' @change="$wire.call('myfunction',$el.options[$el.selectedIndex].dataset.myvalue)">
    <option value="1" data-myvalue="12345">
</select>

Is there a pure livewire solution to this?

,

Your first code snippet is practically there already. The documentation you linked, in which $event is described, even shows why your code snippet doesn’t work:

Your code uses wire:onchange, but Livewire checks for wire:change.

With your example though, you could also use wire:model="foo" and hook into the updatedFoo($newValue) function.

See the lifecycle hooks doc

]