views:

1165

answers:

2

Hey Guys n Gals!

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!

+3  A: 

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");
Tim Down
Thank you but was looking to use prototype as the rest of the code is using prototype!Will keep this in mind in future when using prototype is not a requirement!
sparkyfied
Prototype is just a library. There's no need to use it for everything, and nothing stopping you from mixing regular DOM methods in with your Prototype code.
Tim Down
+1. `select.options.add(new Option('foo','bar'))` is also supported pretty well.
Roatin Marth
+2  A: 
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.

Alsciende
This worked as per what i wanted to do, although for some reason .insert() was not returning the element to be updated so: insert(option).update(myLabel) didn't work. So changed it to: option.update(myLabel);select.insert(option);Work's a treat.
sparkyfied
If you look closely, the _update_ is on the object returned by _new_, not the one returned by _insert_.
Alsciende