$1.16

What is the best way to add options to a select using only jQuery?

Ask a question+
1

What is the best way to add options to <select> using the only jQuery

I’m looking for something that I don’t need a plugin to do, but I would also be interested in the plugins that are out there.

This is what I 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>');
  }
}

A simple solution:

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

1 Answer

1

Consider this code:

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

Your Answer