Skip to content

Instantly share code, notes, and snippets.

@ruliarmando
Created March 3, 2021 10:34
Show Gist options
  • Save ruliarmando/3a48a219916ab5f4a94d79be32cdc6d0 to your computer and use it in GitHub Desktop.
Save ruliarmando/3a48a219916ab5f4a94d79be32cdc6d0 to your computer and use it in GitHub Desktop.
Select2 Ajax Livewire Integration
@props(['url', 'field', 'error', 'selected' => null, 'extra' => null])
<div wire:ignore>
<select {{ $attributes->merge(['style' => 'width:100%', 'class' => 'mt-1 block w-full py-2 px-3 bg-white rounded-md shadow-sm focus:outline-none
sm:text-sm'])->except('wire:model') }}>
@if ($selected)<option value="{{ $selected[0] }}" selected="selected">{{ $selected[1] }}</option>@endif
</select>
</div>
@if (!empty($error))<span class="text-red-500 text-sm">{{ $error }}</span>@endif
@push('scripts')
<script>
window.addEventListener('load', function() {
$('#{{ $attributes->get('id') }}').select2({
allowClear: true,
placeholder: '{{ $attributes->get('placeholder') ?? '' }}',
minimumInputLength: 2,
ajax: {
url: '{{ $url }}',
dataType: 'json',
data: function(params) {
return {
q: params.term,
field: '{{ $field }}',
_type: params._type,
page: params.page,
};
}
}
});
$('#{{ $attributes->get('id') }}').on('change', function(e) {
@this.set('{{ $attributes->wire('model')->value() }}', $(this).select2('val'));
});
});
</script>
@endpush
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment