javascript tutorial - [5 Solutions] Add options to a select from as JS object with jQuery - javascript - java script - javascript array



Problem:

What is the best way to add options to a select from as JS object with jQuery?

Solution 1:

We are looking for something that we don't need a plugin to do, but would also be interested in the plugins that are out there. This is what we did:

selectValues = { "1": "test 1", "2": "test 2" };

for (key in selectValues) {
  if (typeof (selectValues[key] == 'string') {
    $('#mySelect').append('<option value="' + key + '">' + selectValues[key] + '</option>');
  }
)}
click below button to copy the code. By JavaScript tutorial team

A clean/simple solution: This is a cleaned up and simplified

$.each(selectValues, function(key, value) {   
     $('#mySelect')
          .append($('<option>', { value : key })
          .text(value)); 
});

click below button to copy the code. By JavaScript tutorial team

Solution 2:

$.each(selectValues, function(key, value) {   
     $('#mySelect')
         .append($("<option></option>")
                    .attr("value",key)
                    .text(value)); 
});

click below button to copy the code. By JavaScript tutorial team

Solution 3:

var output = [];

$.each(selectValues, function(key, value)
{
  output.push('<option value="'+ key +'">'+ value +'</option>');
});

$('#mySelect').html(output.join(''));

click below button to copy the code. By JavaScript tutorial team

Solution 4:

$.each(selectValues, function(key, value) {
    $('#mySelect').append($("<option/>", {
        value: key,
        text: value
    }));
});


click below button to copy the code. By JavaScript tutorial team

Solution 5:

jQuery

var list = $("#selectList");
$.each(items, function(index, item) {
  list.append(new Option(item.text, item.value));
});
click below button to copy the code. By JavaScript tutorial team

pure javascript

var list = document.getElementById("selectList");
for(var i in items) {
  list.add(new Option(items[i].text, items[i].value));
}

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Add options to a select from as JS object with jQuery