I'm trying to select a value into a select box using Select2 and Ajax autocomplete with Laravel and Blade. I have the problem only on edit-mode (when I already have a value on DB) and it works without problme in insert-mode. Here my html code where the select is empty:
<select class="form-control" id="city-name" name="city" style="width: 100%">
{{ isset($indirizzi->city_id) ? "<option value=\"". $indirizzi->city->id ."\" selected>".$indirizzi->city->name."</option>" : "" }}
</select>
Here my javascript code where I get value from DB and create a new option value:
<script>
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
@if(isset($indirizzi))
var newOption = new Option('{{ $indirizzi->city->name }}', '{{ $indirizzi->city->id }}', true, true);
var txtOption = '<option value="{{ $indirizzi->city->id }}" selected>{{ $indirizzi->city->name }}</option>';
$('#city-name').append(txtOption).val('{{ $indirizzi->city->id }}');
$('#city-name').select2().trigger('change');
@endif
$().ready(function () {
$("#city-name").select2({
ajax: {
url: "{{ route("ajaxFindCity") }}",
dataType: 'json',
delay: 250,
type: "POST",
data: function (params) {
return {
_token: CSRF_TOKEN,
city: params.term
};
},
processResults: function (data) {
return {
results: data
};
},
error: function (data) {
showException(data);
},
cache: true
},
minimumInputLength: 3,
templateSelection: function (data) {
return data.city;
}
});
});
</script>
But on loadind the page I can see the selected value into my selectbox but doesn't work the search of a new value...
This is the code of function into route("ajaxFindCity") that works if I'm not in edit view:
public function ajaxFind(Request $request)
{
// Recupero la città da ricercare
$city = $request->get("city");
// Recupero le città che rientrano nella mia ricerca
$cities = City::with('province')->where('cities.name', 'like', $city . '%')->get();
$result = [];
foreach ($cities as $city) {
$result[] = [
"id" => $city->id,
"text" => $city->name . " (" . $city->province->code . ")",
"city" => $city->name,
"province" => $city->province->code
];
}
return response()->json($result);
}
route("ajaxFindCity")
- Christophe Hubert<option value="3620194" selected="selected">select2/select2</option>
so you can remove your@if(isset($indirizzi))
condition. - Christophe Hubert