Fill in a Dropdown (Select)

Asked

Viewed 656 times

1

I need to create a select In this pattern:

<select id="Cidades">
    <option></option>
</select>

Where the user will select its state, and then a jquery will be made that searches the cities according to the selected state. so far I can do (but not yet done), my problem is how would I send the return data of json to the dropdown (Select), and I wanted to know if the select the above is also correct to fill in the data.

  • 2

    you already asked a question very similar to that last week, I did an update on my answer see if it doesn’t help you. Then you can remove that question =]

  • because it is @Brunno kkk but as the scope has changed, I preferred to ask a new question, even if I tried to ask another question on top of a question and I was criticized. but thanks. when you get home I see ;) Thanks Even. Ah if you can help me in this other Question

1 answer

2


    $.ajax({
        type: ...,
        url: ...,
        datatype: "Json",
        data: { ... },
        success: function (data) {
            if (data.length > 0) {
                $.each(data, function (index, value) {
                    $('#Cidades').append('<option value="' + value.Id+ '">' + value.Nome + '</option>');
                });
            } else {
                var novaOpcao = $('<option value=""></option>');
                $('#Cidades').append(newOption);
            }
        }
    });

The return enters the callback Success. It uses a loop for each city returned in Json. I put as value. id and value. Name to reference the properties of the City entity, but if it is another just adjust.

"Else" forces a null option if there are no cities registered for that state, hence it facilitates validation at least of the front end if you have defined this.

  • It worked, but if I click more than once on the button, it fills in the data by duplicating everything. I believe I would have to clear this list first, before adding again. You know how I can do?

Browser other questions tagged

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