Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want a to add an option dynamically to a 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 lightweight 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?

like image 306
jamesmhaley Avatar asked Jan 26 '10 13:01

jamesmhaley


People also ask

What do you use to get the currently selected option in a select box in JavaScript?

var yourSelect = document. getElementById("your-select-id"); alert(yourSelect. selectedOptions[0]. value);


2 Answers

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");
like image 184
Tim Down Avatar answered Oct 01 '22 12:10

Tim Down


select.insert(new Element('option', {value: myValue}).update(myLabel));

insert appends to the content of the select object, update updates the content of the new option object.

Not really better than the classic way, though.

like image 27
Alsciende Avatar answered Sep 29 '22 12:09

Alsciende