Select/Multiselect using choice.js in laravel livewire not working

Viewed 634

I have using livewire and now I need to create select dropdown with a search option, and I came across choices.js choice.js link and follow this livewire with choice.js link I can make with work (but I have to use wire:ignore) for the select when the data is not dependent on others select (like fetch district after state is selected)

Now I need to fetch district after state is change, and of course i use wire:ignore because of styling and the district cannot display in the option list. If I didn't use wire:ignore then the style is breaking. For the very first time the district display based on state select without breaking any styles, after that district cannot updated even state is changed.

Below are my code for select state and district

<x-input.select wire:model="state" prettyname="state" :options="$allState" selected="('State')" placeholder="Select State*"/>

@if(!is_null($state))
<x-input.select wire:model="district" prettyname="district" :options="$allDistrict" selected="('District')" placeholder="Select District*"/>
@endif

and in Component

public function updatedState($state)
{
  $this->allDistrict = District::where('state_id', $state)->pluck('id','name')->toArray();
}

The function updatedState() is trigger but the districts value cannot display in the blade file except the first time

the view component for <x-input.select /> is below

<div x-data wire:ignore x-init="() => {
var choices = new Choices($refs.{{ $attributes['prettyname'] }}, {
    itemSelectText: '',
});
choices.passedElement.element.addEventListener(
  'change',
  function(event) {
        values = event.detail.value;
        @this.set('{{ $attributes['wire:model'] }}', values);
  },
  false,
);
let selected = parseInt(@this.get{!! $attributes['selected'] !!}).toString();
choices.setChoiceByValue(selected);
}"
>
<select id="{{ $attributes['prettyname'] }}" wire-model="{{ $attributes['wire:model'] }}" wire:change="{{ $attributes['wire:change'] }}" x-ref="{{ $attributes['prettyname'] }}">
    <option value="">{{ isset($attributes['placeholder']) ? $attributes['placeholder'] : '-- Select --' }}</option> 
    @if(count($attributes['options'])>0)
        @foreach($attributes['options'] as $key=>$option)
            <option value="{{$key}}" >{{$option}}</option>
        @endforeach
    @endif
</select>
</div>

My question is how to get district value based on state data, and not breaking style and which can be searchable?

Thanks in advance

0 Answers
Related