views:

46

answers:

5

How to determine what is selected in the drop down? In Javascript.

+7  A: 

If your dropdown is something like this:

<select id="thedropdown">
  <option value="1">one</option>
  <option value="2">two</option>
</select>

Then you would use something like:

var a = document.getElementById("thedropdown");
alert(a.options[a.selectedIndex].value);

But a library like jQuery simplifies things:

alert($('#thedropdown').val());
cambraca
Just `a.value` would do.
casablanca
I'm digging deep in my memory here, but I think `a.value` didn't work in some browsers (probably IE 6, haha). Anyway, using a library is best.
cambraca
@cambraca: It works on all browsers that I know of, including IE6. (just tested)
casablanca
It happened in very old browsers like Netscape Navigator 4. [Look](http://bytes.com/topic/javascript/answers/90872-how-get-selected-value-select-using-dom)
cambraca
A: 

Like this:

$dd = document.getElementById("yourselectelementid");
$so = $dd.options[$dd.selectedIndex];
Pablo Santa Cruz
A: 
var dd = document.getElementById("dropdownID");
var selectedItem = dd.options[dd.selectedIndex].value;
Soufiane Hassou
+2  A: 

Use the value property of the <select> element. For example:

var value = document.getElementById('your_select_id').value;
alert(value);
casablanca
A: 
<select onchange = "selectChanged(this.value)">
  <item value = "1">one</item>
  <item value = "2">two</item>
</select>

and then the javascript...

function selectChanged(newvalue) {
  alert("you chose: " + newvalue);
}
Thomas F.