What's the easiest way to add an option to a dropdown using javascript? Can this work?
$("#mySelect").append('<option value=1>My option</option>');
What's the easiest way to add an option to a dropdown using javascript? Can this work?
$("#mySelect").append('<option value=1>My option</option>');
I believe that's the easiest way. You might be interested in this cheat sheet (PDF) on using jQuery with selects for more info.
That works well.
If adding more than one option element, I'd recommend performing the append once as opposed to performing an append on each element.
If the option name or value is dynamic, you won't want to have to worry about escaping special characters in it; in this you might prefer simple DOM methods:
var s= document.getElementById('mySelect');
s.options[s.options.length]= new Option('My option', '1');
I agree Ashish, this did NOT work in IE8 (yet did in FF):
$("#selectList").append(new Option("option text", "value"));
This DID work:
var o = new Option("option text", "value"); /// jquerify the DOM object 'o' so we can use the html method $(o).html("option text"); $("#selectList").append(o);