Javascript 如何获取javascript中选择下拉列表的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3971038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the value of a select drop down in javascript?
提问by Sam
How can I alert the value selected by user from a select drop down box in Javascript. In this example I want to store the value inside a variable and alert it to the user.
如何从 Javascript 的选择下拉框中提醒用户选择的值。在这个例子中,我想将值存储在一个变量中并向用户发出警报。
<script type="text/javascript">
function processmyform() {
var chosenAnimal = // what goes here
alert(chosenAnimal);
}
</script>
<form action="">
<select name="animal" class="favAnimal">
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="bird">Bird</option>
</select>
<a href="#" onclick="processmyform()" />
</form>
回答by Gabriel McAdams
First off, it would be easier if your select box had an id. Then you could use getElementById
.
首先,如果你的选择框有一个 id 会更容易。然后你可以使用getElementById
.
var animalSelectBox = document.getElementById('animal');
alert(animalSelectBox.options[animalSelectBox.selectedIndex].value);
Instead, here is how to do it using getElementsByName
(notice this one is plural).
相反,这里是如何使用getElementsByName
(注意这个是复数)。
var arr = document.getElementsByName('animal'); //will be an array
alert(arr[0].options[arr[0].selectedIndex].value);
回答by Tim Goodman
I'd generally put an id on the select, like id="animal"
我通常会在选择上放一个 id,比如 id="animal"
Then you could do:
那么你可以这样做:
var animal = document.getElementById("animal");
var animalValue = animal.options[animal.selectedIndex].value;
alert(animalValue);
回答by Onkelborg
I would set an id on your select-tag:
我会在你的选择标签上设置一个 id:
<select id="animal" name="animal" class="favAnimal">
Javascript:
Javascript:
var chosenAnimal = document.getElementById("animal").value;
alert(chosenAnimal);
回答by Harmen
Use selectedIndex
用 selectedIndex
<form id="yourForm" action="#">
<select id="animal" name="animal" class="favAnimal">
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="bird">Bird</option>
</select>
<input type="submit" value="Submit" />
</form>
window.onload = function(){
var selectElement = document.getElementById('animal');
document.getElementById('yourForm').onsubmit = function(){
var index = selectElement.selectedIndex;
alert(selectElement.options[index].value);
alert(selectElement.options[index].text);
alert(index);
return false;
};
};