Search code examples
laravellaravel-livewire

Laravel Livewire javascript code after model is load


I have one Laravel Livewire model open as bellow code

public function confirmItemAdd() 
{
    $this->resetValidation();
    $this->confirmingItemAdd = true;
}

and my model window code in blade is

<x-jet-dialog-modal wire:model="confirmingItemAdd">

I have one select2 in model and want to set value of select2 on variable name $s2v After search I findout that

$('.select2').val(s2v).trigger('change');

how can I set value of select2 on load on model?

Thanks


Solution

  • You can trigger a browser event from the livewire component and listen for that event and change the select2 value accordingly (assuming the select2 part is wire:ignored).

    
    public $s2v = 'Test value';
    
    public function confirmItemAdd() 
    {
        $this->resetValidation();
        $this->confirmingItemAdd = true;
        $this->dispatchBrowserEvent('change-select2', $this->s2v);
    
    }
    
    

    in your layout file or with the stack in layout file you can listen for this event and trigger the change for the select2 as below,

    <script>
      $(window).on('change-select2', (e) => {
          $('.select2').val(e.detail).trigger('change');
       });
    </script>
    
    

    Note e.detail is the $s2v value passed from the livewire component.