Ok, there were no good straight forward references on google. So…here’s how you do it…
I have a select box…
<select>
<option value=1>One</option>
<option value=2>Two</option>
</select>
when the user selects any option I wan to get the value of the option (I’m trying to evaluate the option value and then based on the selection, show the user another part of the form..)
So in your select tag you drop in:
onchange="this.options[this.selectedIndex].value"
- “onchange=” – this is triggered when the user changes the option in a select box (onclick is not supported in IE)
- “this.options” – this gets you the array of options in your select tag, here this would be: [1,2]
- “this.selectedIndex” – this gets you the index of the item selected…so if the user selects option “One” this.selectedIndex=0, for the first element in the array of options.
- “.value” – this just gets me the value of the option, here that’s either 1 or 2. If you want the text (“One” or “Two”) use “.text”
So lets put it together (i’ll add my conditional showing of another piece of the form too):
<select onchange="if( this.options[this.selectedIndex].value=='1')
;
{Element.show('another_piece')}
else
{Element.hide('another_piece'}">
<option value=1>One</option>
<option value=2>Two</option>
</select>
Hahha, u’ve saved my time :)
Thanks a lot
regards
Select Multiple Form Fields and Finding a better solution for multiple selection with Jquery.
http://www.ryancramer.com/journal/entries/select_multiple/
It’s much easier to get the value simply as follows:
onChange = ‘alert(this.value)’;
@Stefan I don’t see where this would help you solve the problem I described. Using alert doesn’t get you pragmatic access to the value the user chose.
Also, this problem can be solved better with jQuery: http://api.jquery.com/change/
Hi Tyler, Sorry for taking such a long time to reply. (Apparently I didn’t confirm wordpress subscription, so I wasn’t notified of responses).
What I meant was that instead of using:
this.options[this.selectedIndex].value
you could just use:
this.value
thanks a lot dude!