onChange select2 in livewire 3 dose not working
you can solve this problem in two ways, 1) set & 2) dispatch. Let's see,
Set
app/Livewire/Category.php
class Category extends Component
{
public string $categoryId = "null";
public function render()
{
return view('livewire.category');
}
}
resources/views/livewire/category.blade.php
<div wire:ignore>
<label>
Category
</label>
<select
name="category_id"
id="category_id"
wire:model="categoryId"
data-control="select2"
data-placeholder="Select a Category..."
>
<option value="">Select a Category...</option>
<option value="1">Apple</option>
<option value="2">Oppo</option>
<option value="3">Vivo</option>
</select>
</div>
<script>
document.addEventListener('livewire:init', () => {
$('#category_id').on('select2:select', function (e) {
let value = $(this).val();
@this.set('categoryId', value);
});
});
</script>
now if you change the select2 option the value will update. you can do this another way by using dispatch. Let's see
Dispatch
app/Livewire/Category.php
use Livewire\Attributes\On;
class Category extends Component
{
public string $categoryId = "null";
#[On('category-id')]
public function updateProduct($category_id = null): void
{
$this->categoryId = $category_id;
}
public function render()
{
return view('livewire.category');
}
}
resources/views/livewire/category.blade.php
<div wire:ignore>
<label>
Category
</label>
<select
name="category_id"
id="category_id"
wire:model="categoryId"
data-control="select2"
data-placeholder="Select a Category..."
>
<option value="">Select a Category...</option>
<option value="1">Apple</option>
<option value="2">Oppo</option>
<option value="3">Vivo</option>
</select>
</div>
<script>
document.addEventListener('livewire:init', () => {
$('#category_id').on('select2:select', function (e) {
let value = $(this).val();
//@this.set('categoryId', value);
Livewire.dispatch('category-id', { category_id: value });
});
});
</script>
I hope this will help you to solve your problem.
Note: use wire:ignore in the select2 root div otherwise it will disappear when you submit the form.