Livewire with Select2

When you use Livewire, it could be tricky, to use jquery plugins. But hey, here is a short trick, how to use Select2 with Livewire.

First of all, you have to add the following part in your layout, after @livewireScripts.

<!-- This should be added after the livewire scripts part -->

With the help of this, you can push javascript snippets to the right place. At your component you have a select input, similar to the following:

<div wire:ignore class=""> 
  <label class="" for="productSearch">Place Product name:</label> 
  <select class="select2 productSearchClass" name="productSearch" id="productSearch"> 
  <option value="" selected>Select</option> 
  @foreach($searchForProducts as $searchForProduct) 
    <option value="{{$searchForProduct->id}}"> 

The most important part is, the wire:ignore at the main div.

Now at the end of the livewire component, you should have the following snippet:

  $(document).ready(function() { 
    $('.productSearchClass').on('change', function (e) { 
      @this.set('productSearch', e.target.value);

The snippet above is easy.

  • It adds select2 style and functions to the productSearch class.
  • Whenever it changes, a set method will transfer it's value to te productSearch Livewire public attribute.

That's all! Have a nice day!

© 2024 PappZ. All rights reserved.