Clear city variable when selecting another state

Asked

Viewed 43 times

-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:

  1. When you select the state, the selected city is any one, not the first one on the list.
  2. 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>");
                });

        },

1 answer

1

I don’t recommend bringing the first selected city, this may induce the user to the error of selecting an unwanted city, so leave a "Select a city" option" (selected) and as not selectable (disabled) if mandatory (if not mandatory disabled in this option).

The first thing you will need to do is clear the list of cities whenever a new state is selected (this should be at the beginning of your function)

$("#cidade").html("<option selected disabled>Selecione</option>")

After this cleaning, you will be ready to add the new cities to your select. with Success data in your Ajax

Browser other questions tagged

You are not signed in. Login or sign up in order to post.