Popular dynamically select form

Asked

Viewed 214 times

0

I have an appointment that returns a array where I want to popular a select dynamically, but by the code below it Undefined

for(var i = 0; i <= cidades.length; i++){
            var html = "";
            html += "<option>" + cidades[i] + "</option>";    
            document.getElementById("cidade").append(html);
        }

inserir a descrição da imagem aqui

2 answers

1

The "city" element is a select so and add html as he would in an element div perhaps not the best option, creating the elements option and add would be more readable:

for(var i = 0; i <= cidades.length; i++){
    var selectCidade = document.getElementById("cidade");
    var option   = document.createElement("option");
    option.value = cidades[i];
    option.text  = cidades[i];
    selectCidade.appendChild(option);
}

1


Your for is going through once more, and I also believe that the method append will not work on elements of type select, try to modify the innerHTML his.

Below is an example:

for(var i = 0; i < cidades.length; i++)
{
    var html = '<option>'+cidades[i]+'</option>';
    document.getElementById('cidade').innerHTML += html;
}

Another cool way to traverse the vector is by using foreach, follow example:

cidades.forEach(function (cidade) {
    var html = '<option>'+cidade+'</option>';
    document.getElementById('cidade').innerHTML += html;
});

Browser other questions tagged

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