最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Selecting value of <select> tag in javascript. problem - Stack Overflow

programmeradmin5浏览0评论

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

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

Share Improve this question edited Jul 13, 2009 at 20:57 Alex Rozanski 38k10 gold badges69 silver badges69 bronze badges asked Jul 13, 2009 at 20:53 Zeeshan RangZeeshan Rang 19.9k29 gold badges74 silver badges103 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

If selecting by Id, you should use :

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

   alert(sel.options[sel.selectedIndex].value); 
}

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); 
}
发布评论

评论列表(0)

  1. 暂无评论