Adding an Option to a Select Element with javascript using the Prototype library

jamesmhaley picture jamesmhaley · Jan 26, 2010 · Viewed 21.6k times · Source

Want a to add an option dynamically to an Select element using prototype.

There seems to be a lot of different ways to do it out there, all to do with options.add etc... Not seen much in the way of cross-browser ways.

Want it to be as light-weight as possible.

This is what I have got so far. It's just the appending the options that i'm stuck on:

var oNewOption = new Element('option').value=vItem;
oNewOption.text=vItem;

Any ideas anyone?

Thanks in advance!

Answer

Tim Down picture Tim Down · Jan 26, 2010

No need for Prototype, it'll be just as easy with the following time-honoured method that works in every major desktop browser since the mid-1990s:

// Assuming a select element stored in a variable called 'select'
select.options[select.options.length] = new Option("Option text", "optionValue");