views:

497

answers:

2

Hello.

I have an external Javascript file and i am trying to alert the value of select tag.

My <select> code looks like this:

<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 the 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  A: 

If selecting by Id, you should use :

function castvote() { 
   var sel = document.getElementById("vote");

   alert(sel.options[sel.selectedIndex].value); 
}
Philippe Leybaert
You didn't change the 2nd instance of document.vote
cdm9002
this does not works. tried it.
Zeeshan Rang
I fixed it for him- it got the point across anyway.
Joel Coehoorn
@cdm9002: fixed it by introducing a variable. Thanks
Philippe Leybaert
@joel: seems you were changing the same thing as me at the same time :)
Philippe Leybaert
thanks it works now
Zeeshan Rang
+1  A: 

Easy way, change your code so that your 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();">

Better way, change your javascript so it is retreiving the select box by its ID rather than through the document object:

function castvote() {
    var mySelect = document.getElementById("vote"); 
    alert(mySelect.options[mySelect.selectedIndex].value); 
}
Matt Bridges