Popular select dynamically

0

I have a query that returns a array where I want to pop a select dynamically, but by the code below it gives undefined

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

    
asked by anonymous 23.05.2018 / 19:57

2 answers

1

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

  

Here 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 get around the vector is by using forEach, following example:

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

The element "city" is a select so adding html to it as you would in a div element might not be 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);
}
    
23.05.2018 / 20:01