Search code examples
alpine.js

BladewindUI with Alpine JS


sorry if this is silly to ask but i haven't found any solution to this question of mine. so the code below is i want the page to run something (in this case, just alert on change of select option). if it was normal html, it'll be something like this

<select name="year" @change="alert('dd')">
    <option value="1">1</option>
    <option value="2">2</option>
</select>

but when i used it on bladewind, it doesn't work. it seems to work on some(input) and not on others(toggle)

<x-bladewind::select @change="alert('dd')" name="year" searchable="true" label="Year" :data="$year" />

hence, is it my code that is wrong or some alpine js code is not applicable to bladewind ui? i'm using bladewind ui because i want to use its searchable select features instead of using select2 but at this rate, i think i have to use select2 back


Solution

  • The BladeWindUI Select is not compatible with AlpineJS as unexpected attributes such as @change are ignored.

    A possible solution is to use the onselect attribute managed by the BladeWindUI Select to set an handler which can send a custom event passing the year as a parameter, then intercept the event on the Alpine side and extract the data - or in any case trigger any desired action:

    <div x-data="{year: ''}"
         @set-year.window="year=$event.detail.year; alert('dd')"
    >
       <x-bladewind::select name="year"
                            searchable="true"
                            label="Year"
                            :data="$year"
                            onselect="setAlpineYear"
       />
    
       <div x-text="`Selected year: ${year}`"> </div>
    
    </div>
    
    <script>
        const setAlpineYear = (value) => {
            window.dispatchEvent(new CustomEvent("set-year", {detail: {year: value} }));
        }
    </script>