Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What is the best method for adding options to a <select> from a JavaScript object using 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 clean/simple solution:

This is a cleaned up and simplified version of matdumsa's:

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

Changes from matdumsa's: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().

like image 566
Darryl Hein Avatar asked Oct 04 '08 20:10

Darryl Hein


People also ask

Can we add class in select option in jQuery?

jQuery addClass() MethodThe addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute.

How do I select a specific Dropdownlist using jQuery?

Syntax of jQuery Select Option$(“selector option: selected”); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $(“selector option: selected”).

How do you make a selection in JavaScript?

To select a <select> element, you use the DOM API like getElementById() or querySelector() . How it works: First, select the <button> and <select> elements using the querySelector() method. Then, attach a click event listener to the button and show the selected index using the alert() method when the button is clicked.


2 Answers

The same as other answers, in a jQuery fashion:

$.each(selectValues, function(key, value) {         $('#mySelect')          .append($("<option></option>")                     .attr("value", key)                     .text(value));  }); 
like image 76
matdumsa Avatar answered Sep 23 '22 21:09

matdumsa


var output = [];  $.each(selectValues, function(key, value) {   output.push('<option value="'+ key +'">'+ value +'</option>'); });  $('#mySelect').html(output.join('')); 

In this way you "touch the DOM" only one time.

I'm not sure if the latest line can be converted into $('#mySelect').html(output.join('')) because I don't know jQuery internals (maybe it does some parsing in the html() method)

like image 30
gpilotino Avatar answered Sep 22 '22 21:09

gpilotino