tags:

views:

66

answers:

3

Hello, I have an html list with some items loaded. I am able to get the select list object using the following code var list = document.getElementById('ddlReason');

but I need help with figuring out how to detect which value has been chosen from the list

Thanks

+3  A: 
// Gets your select
var list = document.getElementById('ddlReason');

// Get the index of selected item, first item 0, second item 1 etc ...
var INDEX = list.selectedIndex;

// Viola you're done
alert(list[INDEX].value);

Edit (forgot .value).

You can also make that a bit more concise, but I wanted to make it readable so you could see what was going on. Shorter version:

var list = document.getElementById('ddlReason');
alert(list[list.selectedIndex].value);
Erik
Pretty sure that should be list.options[INDEX].value
Scott Saunders
They both work!
fudgey
In all browsers? I may be about to learn something.
Scott Saunders
+1  A: 

The list object will have a 'options' attribute that is an array of all the options in the list and a 'selectedIndex' attribute that contains the index of the selected item (or the first selected item if there are multiple). So you can do this:

var list = document.getElementById('ddlReason');
var selectedValue = list.options[list.selectedIndex];
Scott Saunders
A: 

This works great, but I think it needs to be alert(list[list.selectedIndex].text); to get the actual Text displayed in the list

Thanks Erik

Alex