For some reason, this select2 element on my page is always selected. Here is the most minimal version:
$(document).ready(function () {
$('#animals').select2({
'multiple': true,
});
$('#business_types').select2({
'multiple': true,
});
});
<div class="mt-2">
{{ \Form::tLabel('', __('Animals'))}}
<select name="animals[]" id="animals">
@foreach($animals as $animal)
<option @if(in_array($animal->id, request()->animals ?? [])) selected @endif value="{{ $animal->id }}">{{ $animal->name }}</option>
@endforeach
</select>
</div>
<div class="mt-2">
{{ \Form::tLabel('', __('Business types'))}}
<select name="business_types[]" id="business_types">
@foreach($business_types as $business_type)
<option @if(in_array($business_type->id, request()->business_types ?? [])) selected @endif value="{{ $business_type->id }}">{{ $business_type->name }}</option>
@endforeach
</select>
</div>
This PHP produces this:
<select name="business_types" id="business_types" data-select2-id="select2-data-business_types" multiple="" tabindex="-1" class="select2-hidden-accessible" aria-hidden="true">
<option value="1" data-select2-id="select2-data-5-kfne">Alimentation</option>
<option value="2">Animaleries</option>
...
</select>
I didn't include the animal select, but it's the same issue: the first element is selected.
I tried removing the PHP and it doesn't help much...
Anyone has an idea on how to fix this?
I just had to set the "multiple" value on the select to fix this issue.
<select name="business_types[]" id="business_types" multiple="multiple">
@foreach($business_types as $business_type)
<option @if(in_array($business_type->id, request()->business_types ?? [])) selected @endif value="{{ $business_type->id }}">{{ $business_type->name }}</option>
@endforeach
</select>