How to add option to a select by Jquery / Javascript

4

I'm trying to create a select that gets its options via JavaScript or jQuery, the data is stored in an array.

Example:

for (i = 0; i <= cidades.length; i++) {
    $('select').append('<option>' + cidades[i] + '</option>');
}

But they do not show up. does append() not work in this case?

    
asked by anonymous 14.10.2015 / 00:42

2 answers

3

The for described in the question will work, you could also do according to the code below:

var cidades = [
    'São Paulo',
    'Rio de Janeiro',
    'Bahia'];

cidades.forEach(function(item){
    $('select').append('<option>' + item + '</option>');
});

Follow the jsfiddle .

Or you can do this if you want to put the value in a better way.

$('select').append($('<option>', {
    value: item,
    text: item
}));
    
14.10.2015 / 00:48
1

var cidades = [
    'São Paulo',
    'Rio de Janeiro',
    'Porto Alegre'];


cidades.forEach(function(item){
    addOption(item)
});

function addOption(valor) {
    var option = new Option(valor, valor);
    var select = document.getElementById("mySelect");
    select.add(option);
}
<select id="mySelect" size="8">
    <option>Montenegro</option>
</select>

<button type="button" onclick="addOption('teste')">Insert option</button>

You can use your:

for (i = 0; i <= cidades.length; i++) {
    $('select').append('<option>' + cidades[i] + '</option>');
}

As follows:

for (i = 0; i <= cidades.length; i++) {
    addOption( cidades[i] );
}
    
14.10.2015 / 01:53