views:

1091

answers:

5

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>');
+6  A: 

I believe that's the easiest way. You might be interested in this cheat sheet (PDF) on using jQuery with selects for more info.

tvanfosson
You are a lifesaver!
StuperUser
+1  A: 

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.

Russ Cam
+2  A: 

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');
bobince
Doesn't look so simple to me!!
Click Upvote
A: 

for whatever reason doing $("#myselect").append(new Option("text", "text")); isn't working for me in IE7+

I had to use $("#myselect").html("text");

A: 

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);

Josh