添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Hello guys,
I’m trying to get the value of select onchange with livewire and select2 jquery but when I start select2 I can’t get the value, without select2 the value gets normally.

Code without select2 working normally:

<select class="form-control @error('tipo') is-invalid @enderror" wire:change="setSomeProperty($event.target.value)" name="tipo" value="{{ old('tipo', @$doc->id_tipo_nota) }}" >
              <option value="">Selecione..</option>
              @forelse ($tnfs as $tnf)
                @if (@$doc->id_tipo == $tnf->id_tipo_nota || old('tipo') == $tnf->id_tipo_nota)
                  <option selected='selected' value="{{ $tnf->id_tipo_nota }}">{{ $tnf->nome }}</option>
                @else
                  <option value="{{ $tnf->id_tipo_nota }}">{{ $tnf->nome }}</option>
                @endif
                @empty
              @endforelse
            </select> 

Code with select2 does not work:

<select class="form-control select2 @error('tipo') is-invalid @enderror" wire:change="setSomeProperty($event.target.value)" name="tipo" value="{{ old('tipo', @$doc->id_tipo_nota) }}" >
              <option value="">Selecione..</option>
              @forelse ($tnfs as $tnf)
                @if (@$doc->id_tipo == $tnf->id_tipo_nota || old('tipo') == $tnf->id_tipo_nota)
                  <option selected='selected' value="{{ $tnf->id_tipo_nota }}">{{ $tnf->nome }}</option>
                @else
                  <option value="{{ $tnf->id_tipo_nota }}">{{ $tnf->nome }}</option>
                @endif
                @empty
              @endforelse
            </select>

Help please.

Hey there. I find a solution for select2 and I’m going to share it with you, hope it solve your problem. In my case I use some js also Livewire like next.
The select element:

<select class="form-control col-sm-6" id="selectCompany">
    //do your stuff
</select>

In the custom script section:

$(document).ready(function() {
            window.initSelectCompanyDrop=()=>{
                $('#selectCompany').select2({
                    placeholder: 'Select a Company',
                    allowClear: true});
            initSelectCompanyDrop();
            $('#selectCompany').on('change', function (e) {
                livewire.emit('selectedCompanyItem', e.target.value)
            window.livewire.on('select2',()=>{
                initSelectCompanyDrop();

and in component:

public $company;
protected $listeners = [
        'selectedCompanyItem',
    public function hydrate()
        $this->emit('select2');
         //.......
public function selectedCompanyItem($item)
        if ($item) {
            $this->company = Company::find($item);
            $this->emit('selectedCompanyId', $this->company->id);
            $this->company = null;

and that’s all…for me work perfectly