Getting the value of a selected option

634 views
Skip to first unread message

skunkbad

unread,
Jul 7, 2009, 10:44:55 PM7/7/09
to Prototype & script.aculo.us
I've got a standard select box with options, and the select box has an
id of "theme_choice"

I've found the following script online, but it isn't popping up an
alert when a selection is made:


$$('#theme_choice').each(function(elem){
if (elem.selected) alert(elem.text + ' ' + elem.value);
});


Prototype is called just before this in the head area of the page. I'm
using the latest version RC3.

This is for a theme changer script on my website. I have a current
theme changer script, but I'm trying to play around with prototype.

I don't know if it is spam to put a link to my website or reference
it, so I won't, but the select box with options is really just a
standard form element. Nothing special.

Thanks for your help.

T.J. Crowder

unread,
Jul 8, 2009, 3:36:35 AM7/8/09
to Prototype & script.aculo.us
Hi,

> I've found the following script online, but it isn't popping up an
> alert when a selection is made:

You're not asking it to. :-) You're asking it to pop up an alert if
something is selected at the moment you're calling that code; you
haven't hooked up an event handler. To make it happen when something
is selected, you'll need to observe the 'change' event (probably).
You probably also want $('theme_choice') rather than $$
('#theme_choice')[1][2]. More here[3][4].

[1] http://prototypejs.org/api/utility/dollar
[2] http://prototypejs.org/api/utility/dollar-dollar
[3] http://prototypejs.org/api/element/observe
[4] http://prototypejs.org/api/event/observe

HTH,
--
T.J. Crowder
tj / crowder software / com
Independent Software Engineer, consulting services available

ColinFine

unread,
Jul 9, 2009, 9:36:58 AM7/9/09
to Prototype & script.aculo.us
Incidentally, (not answering your question, which TJ has done)

> $$('#theme_choice').each(function(elem){
>                                 if (elem.selected) alert(elem.text + ' ' + elem.value);
>                 });

"$$('#something')"

while valid, is almost always wrong. It says "give me a list of all
the elements with id 'something'". But by definition there can be only
one such element, so it is simpler to replace your code with

elem = $(''theme_choice');
if (elem.selected) ...

If you are using this because you have multiple entities with the same
id, then your page is not valid HTML, and browsers may not behave
identically with it.
Reply all
Reply to author
Forward
0 new messages