Using Livewire with Select2 Selectpicker

Hey, if anyone is wondering how to use Livewire with older jQuery based extensions like DateTimePicker, it’s actually pretty easy in many cases.

I have projects where I’m using bootstrap themes, and a very common input for me is a selectpicker

The docs give a great writeup of how to do this:

Here’s the relevant code from the docs:

Basically you need to tell Livewire to ignore your original select item and then use javascript to hook into the changed event on your select picker. You can see the blade directive @this.set('foo', e.target.value); which is what tells your Livewire Class to set the value of your public property to what was chosen in the selectpicker.

I’ve used the same approach for datetimepickers and it works just as well.

1 Like

Hi; How would you do that if you have select multiple?
For example, you are editing a form. Need to load old data and add one more record?

The solution is:

<script>
    $(document).ready(function() {
        $('#select2').select2();
        $('#select2').on('change', function (e) {
            var data = $('#select2').select2("val");
            @this.set('foo', data);
        });
    });
</script>

How would you deal with the case when you select a value it re-renders the component and then it is no longer a select2 but a normal select?