skip to Main Content

I use select2 to style selects. But in livewire I faced a problem that when I change the value it doesn’t change even though the select is set to model

<div class="select2-custom-field select2-without-search">
                <select class="form-control height-40" wire:model="interval">
                    @foreach(AppModelsSavedSearch::listInterval() as $key => $value)
                        <option {{$key == AppModelsSavedSearch::INTERVAL_WEEK ? 'selected' : ''}} value="{{$key}}">{{$value}}</option>
                    @endforeach
                </select>
            </div>

I tried adding onchange="@this.call(‘changeInterval’, $(this).val());", but then the select, after selecting the value, looks like normal.

Can this be fixed?

2

Answers


  1. Have you tried changing how the selected option is defined in the options tag? As the styling shouldn’t normally interfere with livewire assignment to component properties.

    <option @if($key == AppModelsSavedSearch::INTERVAL_WEEK ) selected @endif value="{{$key}}"> {{$value}} </option>
    
    Login or Signup to reply.
  2. I assume you are using Livewire 3

    Add a wire:ignore in the outer <div>

    <div wire:ignore class="select2-custom-field select2-without-search">
        .....
    

    or alternatively you can wrap that <div> with an outer <div> containing the wire:ignore attribute:

    <div wire:ignore
        <div class="select2-custom-field select2-without-search">
            .....
        </div>
    </div>
    

    In this way Livewire will not update the <select> which is already managed by the select2

    Then to update the $interval variable you can set it on the frontend side using the $wire object:

    @script
    <script>
    
        // using $wire.set the value is sent immediately to the backend like wire:model.live
        $(() => { $(".select2-custom-field select").on("change", (e) => {
            $wire.set("interval", e.target.value);
        })});
    
        // alternatively the value can be set locally and can be updated when you apply an explicit update (like a submit) 
        // $(() => { $(".select2-custom-field select").on("change", (e) => {
        //     $wire.interval = e.target.value;
        // })});
    
    
    </script>
    @endascript
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search