Update Select2 dropdown based on previous input

What seems to be the problem:
Currently I am using wire:ignore in my select2. One select2 input is dependent on the previous input. For example I have 2 inputs, one for region and other for technicians. There are many technicians throughout different regions. If I select a region, the technicians should get filtered out based on the region selected. If I remove the wire:ignore it does update the select based on the query in render method, but the select2 goes away. I saw an implementation where they added livewire:hook in script to check for message.processed, however there was an error saying Uncaught (in promise) TypeError: $(…).select2 is not a function.

Steps to Reproduce:
select2 goes away after selecting the first option
Are you using the latest version of Livewire:
yes
Do you have any screenshots or code examples:

{{-- Nothing in the world is as soft and yielding as water. --}}

<div class="mt-3 row">

    <div class="form-group col-md-6">

        <label for="regions">Select Region</label>

        <!--  <input type="text" wire:model="search" id="serial"> -->

        <select class="select2" style="width: 100% !important" id="regions" wire:model='regionSelect'>

            <option></option>

            @foreach($regions as $region)

                <option value="{{ $region->id }}">{{ $region->title }}</option>

            @endforeach

        </select>

    </div>

    <div class="form-group col-md-6">

        <label for="stations">Select Station</label>

        <!--  <input type="text" wire:model="search" id="serial"> -->

        <select class="select2" style="width: 100% !important" id="stations" wire:model='stationSelect'>

            <option></option>

            @foreach($stations as $station)

                <option value="{{ $station->id }}">{{ $station->name }}</option>

            @endforeach

        </select>

    </div>

</div>

<button wire:click="submit()" class="btn btn-primary">Submit</button>

@push(‘scripts’)

<script>

document.addEventListener('livewire:load', function (event) {

    Livewire.hook('message.processed', () => {

        $('.select2').select2();

    });

});

$('.select2').select2();

</script>

@endpush

Did you reference the assets css and js of select2?

yes I did in the main base blade.

try this on script tag

$(document).ready(function() {
            window.initSelectStationDrop=()=>{
                $('#stations').select2();
            }
            initSelectStationDrop();
            window.livewire.on('select2',()=>{
                initSelectStationDrop();
            });

        });

and in component

public function hydrate()
    {
        $this->emit('select2');
    }
2 Likes