How do I add options to a DropDownList using jQuery?
With no plug-ins, this can be easier without using as much jQuery, instead going slightly more old-school:
var myOptions = {
val1 : 'text1',
val2 : 'text2'
};
$.each(myOptions, function(val, text) {
$('#mySelect').append( new Option(text,val) );
});
If you want to specify whether or not the option a) is the default selected value, and b) should be selected now, you can pass in two more parameters:
var defaultSelected = false;
var nowSelected = true;
$('#mySelect').append( new Option(text,val,defaultSelected,nowSelected) );
With the plugin: jQuery Selection Box. You can do this:
var myOptions = {
"Value 1" : "Text 1",
"Value 2" : "Text 2",
"Value 3" : "Text 3"
}
$("#myselect2").addOption(myOptions, false);
Without using any extra plugins,
var myOptions = {
val1 : 'text1',
val2 : 'text2'
};
var mySelect = $('#mySelect');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
If you had lots of options, or this code needed to be run very frequently, then you should look into using a DocumentFragment instead of modifying the DOM many times unnecessarily. For only a handful of options, I'd say it's not worth it though.
------------------------------- Added --------------------------------
DocumentFragment
is good option for speed enhancement, but we cannot create option element using document.createElement('option')
since IE6 and IE7 are not supporting it.
What we can do is, create a new select element and then append all options. Once loop is finished, append it to actual DOM object.
var myOptions = {
val1 : 'text1',
val2 : 'text2'
};
var _select = $('<select>');
$.each(myOptions, function(val, text) {
_select.append(
$('<option></option>').val(val).html(text)
);
});
$('#mySelect').append(_select.html());
This way we'll modify DOM for only one time!