Get the value of a selected option with Javascript

Rails, Ruby

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>
;

Advertisements

6 thoughts on “Get the value of a selected option with Javascript

      1. 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s