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


what best method adding options select json object using jquery?

i'm looking don't need plugin do, interested in plugins out there.

this did:

selectvalues = { "1": "test 1", "2": "test 2" };  (key in selectvalues) {   if (typeof (selectvalues[key] == 'string') {     $('#myselect').append('<option value="' + key + '">' + selectvalues[key] + '</option>');   } } 

a clean/simple solution:

this cleaned , simplified version of matdumsa's:

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

changes matdumsa's: (1) removed close tag option inside append() , (2) moved properties/attributes map second parameter of append().

same other answers, in jquery fashion:

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

Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -