Fill in a Dropdown (Select)

1

I need to create a select In this pattern:

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

Where the user will select his state, and then there will be a jquery that searches the cities according to the selected state. so I can do this (but I have not done it yet), my problem is how I would send the json return data to the dropdown (Select), and I wanted to know if the top select is also correct to fill in the data. / p>     

asked by anonymous 21.11.2016 / 23:11

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 it as value.Id and value.Name to reference the properties of the City entity, but if it is another, just adjust.

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

    
22.11.2016 / 01:13