Ask Your Question
3

What is the process of using Choices.js with Livewire for selecting multiple options?

asked 2023-01-02 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-08-22 03:00:00 +0000

bukephalos gravatar image

To use Choices.js with Livewire for selecting multiple options, you can follow the below steps:

  1. Install Choices.js: First, you need to install Choices.js to your project using npm.

  2. Import Choices.js: Import the Choices.js in your component.

  3. Create a select element: Create a select element in your component and assign wire:model property to it.

  4. Wire the select element to your component property: Define a public property in your component for storing the selected values.

  5. Initialize Choices: Initialize the Choices instance and provide the select element in the constructor.

  6. 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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-01-02 11:00:00 +0000

Seen: 9 times

Last updated: Aug 22 '21