Assign selected item to a select

3

I have the following code:

$("#cep").on('mouseout', function() {

    var url = "http://cep.republicavirtual.com.br/web_cep.php";
    var cep = $(this).val();

    $.ajax({
        type: "GET",
        dataType: 'json',
        data: {'cep': cep, 'formato': 'json'},
        async: false,
        url: url,
        success: function(response) {

            if (response.resultado === '1') {

                $("#bairro").val(response.bairro);
                $("#endereco").val(response.logradouro);

                var uf = response.uf;
                $("select#estado option").each(function() {
                    this.selected = (this.text === uf);
                });

                $("#estado").trigger("change");

                var cidade = response.cidade;

                $("select#cidade option").each(function() {
                    this.selected = (this.text === cidade);
                    console.log(this.selected);
                });

            }

        }
    });

});

In this part of the code should be "set" the city in the combo that was returned via ajax. Note that this part comes after $("#estado").trigger("change") ;

var cidade = response.cidade;

$("select#cidade option").each(function() {
   this.selected = (this.text === cidade);
});

It does not work, cities are populated, the city comes normally but is not set to default in the combo box.

How to solve this?

    
asked by anonymous 15.02.2014 / 14:11

2 answers

2

It might work by putting the code to run inside a event handler ):

        $("select#cidade").one("atualizado", function(){
            var cidade = response.cidade;
            $("select#cidade option").each(function() {
                this.selected = (this.text === cidade);
                console.log(this.selected);
            });
        });

        $("#estado").trigger("change");

I'm assuming there is a callback for the change event of #status , to modify the list of cities. Therefore, the code that marks the selected option must be after update of the list of cities.

In the above suggestion, we used the jQuery one function so that a new callback to be once , and then discarded.

You will also need to trigger the updated event. Do this in your code. Put the command below immediately after updating the options of select that contains the list of cities in the state:

$("select#cidade").trigger("atualizado");
    
15.02.2014 / 14:26
2

Try using .val()
Remove this code snippet

$("select#cidade option").each(function() {
    this.selected = (this.text === cidade);
    console.log(this.selected);
});

And enter this

$("select#cidade").val(cidade);
    
17.02.2014 / 00:06