10

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Alex
  • 39,265
  • 21
  • 45
  • 42

3 Answers3

5
// 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
  • 20,526
  • 8
  • 45
  • 76
4

Actually you can do this

var list = document.getElementById('ddlReason').value;

and if you make an alert to list, you'll get the value of your select tag.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
2

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
  • 29,840
  • 14
  • 57
  • 64