To use Choices.js with Livewire for selecting multiple options, you can follow the below steps:
Install Choices.js: First, you need to install Choices.js to your project using npm.
Import Choices.js: Import the Choices.js in your component.
Create a select element: Create a select element in your component and assign wire:model property to it.
Wire the select element to your component property: Define a public property in your component for storing the selected values.
Initialize Choices: Initialize the Choices instance and provide the select element in the constructor.
Update selected values: Listen to the 'change' event of the Choices instance and update the selected values in your component property.
Here's an example:
<!-- MyComponent.blade.php -->
<select wire:model="selectedValues" multiple>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
@push('scripts')
<script src="{{ asset('js/choices.min.js') }}"></script>
<script>
document.addEventListener('livewire:load', function () {
const selectEl = document.querySelector('[wire:model="selectedValues"]');
const choices = new Choices(selectEl, {
removeItemButton: true,
});
choices.passedElement.addEventListener('change', function () {
@this.set('selectedValues', choices.getValue());
});
})
</script>
@endpush
// MyComponent.php
class MyComponent extends Component
{
public $selectedValues = [];
public function render()
{
return view('livewire.my-component');
}
}
In the above example, we have created a select element with multiple options and used wire:model
to bind it to our component's property $selectedValues
. We have also imported Choices.js and initialized it in the livewire:load
event listener.
Whenever the selected values change, we update the $selectedValues
property of our component using $this->set('selectedValues', choices.getValue())
.
This is how you can use Choices.js with Livewire for selecting multiple options.
Asked: 2023-01-02 11:00:00 +0000
Seen: 9 times
Last updated: Aug 22 '21