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
Post a Comment