DEV Community

Joseph Makram
Joseph Makram

Posted on • Updated on

Create a select2 input with alpinejs and livewire

In this small article i will show you how to implement a select2 input using Alpine.js and Livewire without any needs for JQuery

So first of all we will use library called Tom Select this is an alternative one for the original one select2 this one is written in native javascript so there is no need for JQuery anymore

After that create a new blade file inside the components directory for example select2.blade.php
Then add this bunch of code

@props(['multiple' => false])

<div {{ $attributes }} wire:ignore x-data="{
    value: @entangle($attributes->wire('model')),
    init(){
        let input = new TomSelect(this.$refs.select, {
            onChange: (value) => this.value = value,
            items: this.value
        });
    }
}">
    <select x-ref="select" {{ $multiple? 'multiple' : '' }}  x-model="value">
        {{ $slot }}
    </select>
</div>
Enter fullscreen mode Exit fullscreen mode

At the end you could now easily use it from your livewire component like this

<x-select2 wire:model="permissions">
    <option value="create-users">Create Users</option>
    <option value="edit-users">Edit Users</option>
</x-select2>
Enter fullscreen mode Exit fullscreen mode

Note: don't forget to include the cdn files

<link href="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/css/tom-select.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/tom-select@2.2.2/dist/js/tom-select.complete.min.js"></script> 
Enter fullscreen mode Exit fullscreen mode

Here is the full code on Github

Top comments (0)