Choosing the value of the <select> tag in javascript. problem

I have an external Javascript file and I try to alert value of select tag.

My <select> code is as follows:

 <select id="vote"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> <input type="button" value="vote" onclick="castvote();"> 

and Javascript (which is external):

 function castvote() { alert(document.vote.options[document.vote.selectedIndex].value); } 

But I get the error "document.vote is undefined".

Can someone help me with this.

Best zeeshan

+6
javascript html
source share
2 answers

When choosing by ID, you should use:

 function castvote() { var sel = document.getElementById("vote"); alert(sel.options[sel.selectedIndex].value); } 
+13
source share

A simple way, change your code so that the form field has a name attribute:

 <select name="vote" id="vote"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> <input type="button" value="vote" onclick="castvote();"> 

The best way to change your javascript so that it returns the select box by its identifier, and not through the document object:

 function castvote() { var mySelect = document.getElementById("vote"); alert(mySelect.options[mySelect.selectedIndex].value); } 
+5
source share

All Articles