How to add option for a select by Jquery/Javascript

Asked

Viewed 20,750 times

4

I’m trying to create a select which receives 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 appear. the append() does not work in this case ?

  • The only thing wrong with your code is that i has to be smaller (<) than cities.length and not smaller or equal (<=). But that wouldn’t stop you from adding the options to your select. Make sure you really have data added to the array, if there really is a select on the page, and if the jQuery library actually loaded it. I also suggest to check if the browser console (F12) shows any error, and if yes copy and add in your question.

3 answers

4

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>');
});

Follows the jsfiddle.

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

$('select').append($('<option>', {
    value: item,
    text: item
}));
  • 1

    but in this way, how is it possible to change or create "value" ?

  • @Dr.G you can pass the value inside the append $('select').append('<option value="+ item +">' + item + '</option>');

  • 1

    I edited the answer and added an example with value :)

2

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] );
}

0

Using the function map and the atribuição via desestruturação:

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

cidades.map(item => {
  $('#select1').append('<option>' + item + '</option>')
});

//Com objetos:

cidades = [{
    id: 1001,
    nome_cidade: 'São Paulo'
  },
  {
    id: 1002,
    nome_cidade: 'Rio de Janeiro'
  },
  {
    id: 1003,
    nome_cidade: 'Bahia'
  }
];

//Usando a função map e desestruturação de javascript:
//Isto aqui é muio maaaaaaaaaaaaassa!
cidades.map(({
  id,
  nome_cidade
}) => {
  $('#select2').append(`<option value='${id}'>${nome_cidade}</option>`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h3>Select 1 Demo (normal)</h3>
<select id="select1"></select>

<h3>Select 2 Demo (Usando Atribuição via desestruturação (destructuring assignment))</h3>
<select id="select2"></select>

REFERENCE:

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Atribuicao_via_desestruturacao
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Browser other questions tagged

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