Ajay_kumar
Ajay_kumar

Reputation: 11

how to fetch value from <select> tag

I have a list like

<select name="operation" id="operation">
  <option value="1">XXXX</option>
  <option value="2">YYY</option>
  <option value="3">ZZZ</option>
</select>

I have to get value "XXXX" if user select an option 1, for 2nd I have to get show "YYYY" and so on. And format should be like in the above means i don't have to change value="1","2","3". I need it in javascript. Thanks

Upvotes: 0

Views: 634

Answers (3)

Canavar
Canavar

Reputation: 48098

Try this to alert selected option's text :

<select name="operation" id="operation" 
        onchange="alert(this.options[this.selectedIndex].text);">
  <option value="1">XXXX</option>
  <option value="2">YYY</option>
  <option value="3">ZZZ</option>
</select>

Upvotes: 0

knittl
knittl

Reputation: 265908

var dropdown = document.getElementById('operation');
var selected = dropdown[dropdown.selectedIndex].text;

probably also check for selectedIndex not being out of bounds

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630627

You can get it by grabbing the <select> then getting the <option> at the .selectedIndex, like this:

var sel = document.getElementById('operation');
var text = sel.options[sel.selectedIndex].text;

You can test it out here.

Upvotes: 2

Related Questions