Livewire Nice Select
Nice Select is a lightweight jQuery plugin that replaces native select elements with customizable dropdowns. I wanted to make a reactive dropdown with livewire and using the nice select plugin. But it wasn’t working as expected. Livewire was not able to bind the <select>
to a property.
This happened because nice select is a jQuery plugin and emits jQuery events, and not native DOM events. Livewire normally listens for a native change event when wire:model is attached to an element.
To make this work what I end up doing was to register an event listener manually. It was done like so:
1 <div wire:ignore\>
2<select class\="nice-select"\>
3 <option data-display\="Select"\>Nothing</option\>
4 <option value\="1"\>Some option</option\>
5 <option value\="2"\>Another option</option\>
6 <option value\="3" disabled\>A disabled option</option\>
7 <option value\="4"\>Potato</option\>
8</select\>
9
10</div\>
11
12@section('js')
13<script\>
14 $(document).ready(function() {
15 $('.nice-select').niceSelect();
16 $('.nice-select').on('change', function (e) {
17 @this.set('selectedModel', e.target.value);
18 });
19 });
20</script\>
21@endsection
So right now everytime the select element changes livewire will recieve the event and set the $selectedModel
property to the value of the select element. And also to tell Livewire to skip the DOM-diffing for certain parts of the DOM I used wire:ignore directive on the parent div
.