-1
I have a little doubt.
I have a view that when the user selects a state, loads the list of cities from the database. But it’s having two problems:
- When you select the state, the selected city is any one, not the first one on the list.
- When a state is selected, and has already loaded its cities, if I select another state, it shows the states of the new selected state and the previous one, I am not able to show only the states of the new selected state.
My code:
<div class="form-group row">
<div class="col-sm-6">
<label class="col-sm-2 col-form-label">Estado</label>
<select id="uf" onchange="return buscarMunicipios();" name="uf" type="text" class="form-control upper @error('uf') is-invalid @enderror" required>
<option value="">Selecione</option>
@foreach($states as $state)
<option value="{{$state->id }}" {{ old('uf') == $state->title ? 'selected' : '' }}>{!!$state->title!!}</option>
@endforeach
</select>
</div>
<div class="col-sm-6">
<label class="col-sm-2 col-form-label">Cidade</label>
<select id="cidade" name="cidade" type="text" class="form-control upper @error('cidade') is-invalid @enderror" required>
<option value="">Selecione</option>
</select>
</div>
</div>
Controller:
public function buscarMunicipios() {
$estado_id = \Request::input('estado_id');
$cidades = State::findOrFail($estado_id)->cities->sortBy('titl');
$result = json_encode(['cidades'=>$cidades]);
return response()->json($result);
}
Js:
function buscarMunicipios() {
var token = $("#token").val();
var estado_id = $("#uf").val();
console.log('estado id'+estado_id);
// var json = stringToJson(colaboradores);
// console.log(json);
$.ajax({
url: '/painel/clientes/busca-municipio',
type: 'POST',
method: 'POST',
ContentType: 'application/json',
headers: { 'X-CSRF-TOKEN': token },
data: {'_token': token,'estado_id': estado_id},
beforeSend: function () {
},
success: function (response) {
response = JSON.parse(response);
console.log(response.cidades);
$.each(response.cidades,
function (index, cidade) {
$("#cidade").append("<option selected value=" + cidade.id + ">" + cidade.title + "</option>");
});
},