0
Hello, guys, I have two combos: one states and one cities.
When I choose a state, I search the cities via ajax, as follows:
$('#estados').on('change', function(e){
console.log(e);
var id = e.target.value;
/* busca as cidades de um determinado estado */
$.get("{{ url('/administrador/buscar-cidades') }}/" + id, function(data) {
//esvazia as cidades anteriores
$('#cidades').empty();
$.each(data, function(index,subCatObj){
//console.log(subCatObj);
var option = new Option(subCatObj.nome, subCatObj.id);
$(option).html(subCatObj.nome);
$('#cidades').append(option);
});
});
});
This works perfectly. However, I am using the Windows as backend and have a validation in the controller. If the validation fails, I’m going back to the previous page with the city id and wish the city to be chosen again.
Here is the verification:
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput()->with('idCidade', $request->input('cidade_id'));
}
To do so, I added the following javascript to reload the states:
$(document).ready(function() {
if ($("#estados").find('option:selected').val() != "--Selecione--") {
$("#estados").trigger('change');
}
});
What it does is basically load the cities again if validation fails, to fill the cities. And it works.
The problem now is that I can get the city ID that was previously chosen, which was passed from the controller to the view, and choose the correct city (which had already been chosen before the check).
How to do this?
Thank you for your reply. You gave me a north. I had to add localstorage check in the . done . get, because you need to finish filling out the states first, and then I’ll get a city. I also added a change Trigger in #states when initializing the page. Thanks
– Gabriel Augusto
@Gabrielaugusto Legal! Thank you!
– Sam