Select2 does not work

I implemente select2 in a select as the official documentation indicates and I can’t get it to work in full.

<div>
<div wire:ignore>
    <select class="js-example-basic-single" name="state">
        <option value="AL">Alabama</option>
        <option value="WY">Wyoming</option>
    </select>

    <!-- Select2 will insert it's DOM here. -->
</div>
@push('scripts')
<script>
    $(document).ready(function() {
        $('.js-example-basic-single').select2();
        $('.js-example-basic-single').on('change', function (e) {
            @this.set('foo', e.target.value);
        });
    });
</script>
@endpush

if I remove the following script in the view the select2 component renders fine

$('.js-example-basic-single').on('change', function (e) {
                @this.set('foo', e.target.value);
            });

but of course I lose the desired functionality.

The selct2 add links I use are as follows

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="{{asset('SitioWeb/assets/select2/js/select2.min.js')}}"></script>

Console:

SyntaxError: Invalid or unexpected token, the marked line is the following: @this.set(‘foo’, e.target.value);

what am i missing?

I use this code (my ID’s is has the same name as my variables on Livewire componente):

<div class="col-sm-4" wire:key="UNIQUE_KEY">
<div wire:ignore>
    <label for="select">{{ __('Unidade de Cadência') }}:</label>
    <select id="select" class="form-control">
        <option></option>
        @foreach($selects as $select)
        <option value="{{ $select->id }}"  @if($select == $select->id){{ 'selected' }}@endif>
            {{ $catencyUnit->name }}
        </option>
        @endforeach
    </select>
    @error('select')<span class="error">{{ $message }}</span>@enderror
</div>
</div>

$(document).ready(function () {
    $('#select').select2();
}

$('#select').change(function (e) {
    let elementName = $(this).attr('id');
    @this.set(elementName, e.target.value);
});

document.addEventListener("livewire:load", function (event) {
    window.livewire.hook('afterDomUpdate', () => {
        $('#select').select2();
    });
});

You can use this, if you want. Works perfectly!

1 Like