After Variable validation fails, choose a select option

Asked

Viewed 136 times

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?

1 answer

1


Create a localStorage with the city code on front-end as soon as a city is chosen in the select:

$('#cidades').on('change', function(){
    localStorage.cidade = $(this).val();
});

In the Ajax that carries the States, pull the localStorage if he’s worth anything:

$('#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);
            if(localStorage.getItem("cidade") !== null){
                $('#cidades').val(localStorage.cidade);
            }
        });
    });
});

Don’t forget to erase the localStorage when you no longer need it:

localStorage.removeItem('cidade');
  • 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

  • @Gabrielaugusto Legal! Thank you!

Browser other questions tagged

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