How do I get the selected value from a dropdown list using JavaScript?
如何使用JavaScript从下拉列表中获取所选的值?
I tried the methods below but they all return the selected index instead of the value:
我尝试了下面的方法,但是它们都返回选定的索引而不是值:
var as = document.form1.ddlViewBy.value;
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
//This is one of the simplest form by (Narendra Kottamidde) :
var value = document.getElementById("ddlViewBy").value;
18 个解决方案
#1
2228
If you have a select element that looks like this:
如果你有一个这样的选择元素:
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
Running this code:
运行这段代码:
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
Would make strUser
be 2
. If what you actually want is test2
, then do this:
将使strUser成为2。如果你真正想要的是test2,那么就这样做:
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;
Which would make strUser
be test2
这将使strUser成为test2 ?
#2
267
Plain JavaScript:
纯JavaScript:
var e = document.getElementById("elementId");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
jQuery:
jQuery:
$("#elementId :selected").text(); // The text content of the selected option
$("#elementId").val(); // The value of the selected option
AngularJS: (http://jsfiddle.net/qk5wwyct):
AngularJS:(http://jsfiddle.net/qk5wwyct):
// HTML
<select ng-model="selectItem" ng-options="item as item.text for item in items">
</select>
<p>Text: {{selectItem.text}}</p>
<p>Value: {{selectItem.value}}</p>
// JavaScript
$scope.items = [{
value: 'item_1_id',
text: 'Item 1'
}, {
value: 'item_2_id',
text: 'Item 2'
}];
#3
150
var strUser = e.options[e.selectedIndex].value;
This is correct and should give you the value. Is it the text you're after?
这是正确的,应该给你价值。这是你想要的文本吗?
var strUser = e.options[e.selectedIndex].text;
So you're clear on the terminology:
所以你对术语很清楚:
<select>
<option value="hello">Hello World</option>
</select>
This option has:
这个选项有:
- Index = 0
- 指数= 0
- Value = hello
- 值=你好
- Text = Hello World
- 文本= Hello World
#4
46
The following code exhibits various examples related to getting/putting of values from input/select fields using JavaScript.
下面的代码展示了使用JavaScript从输入/选择字段中获取/输入值的各种例子。
Working DEMO
演示工作
<select id="Ultra" onchange="run()"> <!--Call run() function-->
<option value="0">Select</option>
<option value="8">text1</option>
<option value="5">text2</option>
<option value="4">text3</option>
</select><br><br>
TextBox1<br>
<input type="text" id="srt" placeholder="get value on option select"><br>
TextBox2<br>
<input type="text" id="rtt" placeholder="Write Something !" onkeyup="up()">
The following script is getting the value of the selected option and putting it in text box 1
下面的脚本获取所选选项的值并将其放入文本框1中。
<script>
function run() {
document.getElementById("srt").value = document.getElementById("Ultra").value;
}
</script>
The following script is getting a value from a text box 2 and alerting with its value
下面的脚本从文本框2中获取一个值,并以其值警告。
<script>
function up() {
//if (document.getElementById("srt").value != "") {
var dop = document.getElementById("srt").value;
//}
alert(dop);
}
</script>
The following script is calling a function from a function
下面的脚本从函数调用函数。
<script>
function up() {
var dop = document.getElementById("srt").value;
pop(dop); // Calling function pop
}
function pop(val) {
alert(val);
}?
</script>
#5
20
var selectedValue = document.getElementById("ddlViewBy").value;
#6
18
If you ever run across code written purely for IE you might see this:
如果你遇到过纯粹为IE编写的代码,你可能会看到:
var e = document.getElementById("ddlViewBy");
var strUser = e.options(e.selectedIndex).value;
Running the above in Firefox et al will give you an 'is not a function' error because IE allows you to get away with using () instead of []:
在Firefox中运行上面的操作会给你一个“不是函数”的错误,因为IE允许你使用()而不是():
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
The correct way is to use square brackets.
正确的方法是使用方括号。
#7
12
<select id="Ultra" onchange="alert(this.value)">
<option value="0">Select</option>
<option value="8">text1</option>
<option value="5">text2</option>
<option value="4">text3</option>
</select>
#8
11
Beginners are likely to want to access values from a select with the NAME attribute rather than ID attribute. We know all form elements need names, even before they get ids.
初学者很可能想要从一个带有NAME属性而不是ID属性的select中访问值。我们知道所有表单元素都需要名称,甚至在它们得到id之前。
So, I'm adding the getElementByName()
solution just for new developers to see too.
因此,我添加了getElementByName()解决方案,以便新开发人员也能看到。
NB. names for form elements will need to be unique for your form to be usable once posted, but the DOM can allow a name be shared by more than one element. For that reason consider adding IDs to forms if you can, or be explicit with form element names my_nth_select_named_x
and my_nth_text_input_named_y
.
NB。表单元素的名称将需要是唯一的,以使表单能够在发布时使用,但是DOM可以允许多个元素共享一个名称。由于这个原因,可以考虑添加id,如果可以,或者显式地使用表单元素名my_nth_select_named_x和my_nth_text_input_named_y。
Example using getElementByName
:
使用getElementByName示例:
var e = document.getElementByName("my_select_with_name_ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
#9
10
Just use
只使用
-
$('#SelectBoxId option:selected').text();
for getting the text as listed$(' # SelectBoxId选项:选择')。text();以获取所列出的文本。
-
$('#SelectBoxId').val();
for getting the selected index value$(' # SelectBoxId ').val();获取所选索引值。
#10
7
The previous answers still leave room for improvement because of the possibilities, the intuitiveness of the code, and the use of id
versus name
. One can get a read-out of three data of a selected option -- its index number, its value and its text. This simple, cross-browser code does all three:
前面的答案仍然保留了改进的余地,因为有可能,代码的直观,以及id和名称的使用。我们可以得到一个选定选项的3个数据的读数——它的索引号、它的值和它的文本。这个简单的跨浏览器代码可以做到这三点:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo GetSelectOptionData</title>
</head>
<body>
<form name="demoForm">
<select name="demoSelect" onchange="showData()">
<option value="zilch">Select:</option>
<option value="A">Option 1</option>
<option value="B">Option 2</option>
<option value="C">Option 3</option>
</select>
</form>
<p id="firstP"> </p>
<p id="secondP"> </p>
<p id="thirdP"> </p>
<script>
function showData() {
var theSelect = demoForm.demoSelect;
var firstP = document.getElementById('firstP');
var secondP = document.getElementById('secondP');
var thirdP = document.getElementById('thirdP');
firstP.innerHTML = ('This option\'s index number is: ' + theSelect.selectedIndex + ' (Javascript index numbers start at 0)');
secondP.innerHTML = ('Its value is: ' + theSelect[theSelect.selectedIndex].value);
thirdP.innerHTML = ('Its text is: ' + theSelect[theSelect.selectedIndex].text);
}
</script>
</body>
</html>
Live demo: http://jsbin.com/jiwena/1/edit?html,output .
现场演示:http://jsbin.com/jiwena/1/edit?html输出。
id
should be used for make-up purposes. For functional form purposes, name
is still valid, also in HTML5, and should still be used. Lastly, mind the use square versus round brackets in certain places. As was explained before, only (older versions of) IE will accept round ones in all places.
id应该用于化妆。对于功能形式的目的,名称仍然有效,也在HTML5中,应该仍然使用。最后,注意在某些地方使用方括号和圆括号。正如之前所解释的那样,只有(较老版本的)IE会在所有地方接受圆形的。
#11
5
Refer to the article Selecting dropdown element using JavaScript or jQuery. They have explained it in many ways using JavaScript and jQuery.
请参阅使用JavaScript或jQuery选择dropdown元素的文章。他们在很多方面都用JavaScript和jQuery来解释。
Using jQuery:
使用jQuery:
$(‘select’).val();
#12
3
In 2015, in Firefox, the following also works.
在2015年,在Firefox中,下面的内容也可以使用。
e.options.selectedIndex
e.options.selectedIndex
#13
2
Here is a JavaScript code line:
下面是JavaScript代码行:
var x = document.form1.list.value;
Assuming that the dropdown menu named list name="list"
and included in a form with name attribute name="form1"
.
假设下拉菜单名为list name="list",并以name属性name="form1"的形式包含在表单中。
#14
2
To go along with the above answers, this is how I do it as a one-liner. This is for getting the actual text of the selected option. There are good examples for getting the index number already. (And for the text, I just wanted to show this way)
为了配合上面的答案,这是我作为一个一行人的方式。这是为了获取所选选项的实际文本。有很好的例子可以得到索引号。(对于文本,我只是想以这种方式展示)
var selText = document.getElementById('elementId').options[document.getElementById('elementId').selectedIndex].text
In some rare instances you may need to use parentheses, but this would be very rare.
在一些罕见的情况下,您可能需要使用括号,但这是非常罕见的。
var selText = (document.getElementById('elementId')).options[(document.getElementById('elementId')).selectedIndex].text;
I doubt this processes any faster than the two line version. I simply like to consolidate my code as much as possible.
我怀疑这个过程是否比这两行版本更快。我只是想尽可能地巩固我的代码。
If anyone knows how to do this in one line without having to get the element twice, I would love for you to comment and show me how. I haven't been able to figure that out yet...
如果有人知道如何在一行中做到这一点,而不需要两次得到这个元素,我希望你能对我进行评论,并告诉我该怎么做。我还没弄明白…
#15
2
Running example of how it works:
运行示例:
var e = document.getElementById("ddlViewBy");
var val1 = e.options[e.selectedIndex].value;
var txt = e.options[e.selectedIndex].text;
document.write("<br />Selected option Value: "+ val1);
document.write("<br />Selected option Text: "+ txt);
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3" selected="selected">test3</option>
</select>
Note: The values don't change as the dropdown is changed, if you require that functionality then an onClick change is to be implemented.
注意:当下拉菜单被更改时,值不会改变,如果您需要这个功能,那么onClick更改将被实现。
#16
2
You can use querySelector
.
您可以使用querySelector。
E.g.
如。
var myElement = document.getElementById('ddlViewBy');
var myValue = myElement.querySelector('[selected]').value;
#17
1
The only reason I can see that makes this code not work is if you're using IE7-, and forgot to specify the value attribute for your <option>
-tags... Every other browser should convert what's inside open-close tags as the option value.
我能看到这个代码不工作的唯一原因是如果你使用IE7-,并且忘记为你的 <选项> -标签指定值属性…所有其他浏览器都应该将开放标签内的内容转换为选项值。
#18
-2
Here's an easy way to do it in an onchange function:
这里有一个简单的方法,在一个onchange函数中:
event.target.options[event.target.selectedIndex].dataset.name
event.target.options event.target.selectedIndex .dataset.name
#1
2228
If you have a select element that looks like this:
如果你有一个这样的选择元素:
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2" selected="selected">test2</option>
<option value="3">test3</option>
</select>
Running this code:
运行这段代码:
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
Would make strUser
be 2
. If what you actually want is test2
, then do this:
将使strUser成为2。如果你真正想要的是test2,那么就这样做:
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].text;
Which would make strUser
be test2
这将使strUser成为test2 ?
#2
267
Plain JavaScript:
纯JavaScript:
var e = document.getElementById("elementId");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
jQuery:
jQuery:
$("#elementId :selected").text(); // The text content of the selected option
$("#elementId").val(); // The value of the selected option
AngularJS: (http://jsfiddle.net/qk5wwyct):
AngularJS:(http://jsfiddle.net/qk5wwyct):
// HTML
<select ng-model="selectItem" ng-options="item as item.text for item in items">
</select>
<p>Text: {{selectItem.text}}</p>
<p>Value: {{selectItem.value}}</p>
// JavaScript
$scope.items = [{
value: 'item_1_id',
text: 'Item 1'
}, {
value: 'item_2_id',
text: 'Item 2'
}];
#3
150
var strUser = e.options[e.selectedIndex].value;
This is correct and should give you the value. Is it the text you're after?
这是正确的,应该给你价值。这是你想要的文本吗?
var strUser = e.options[e.selectedIndex].text;
So you're clear on the terminology:
所以你对术语很清楚:
<select>
<option value="hello">Hello World</option>
</select>
This option has:
这个选项有:
- Index = 0
- 指数= 0
- Value = hello
- 值=你好
- Text = Hello World
- 文本= Hello World
#4
46
The following code exhibits various examples related to getting/putting of values from input/select fields using JavaScript.
下面的代码展示了使用JavaScript从输入/选择字段中获取/输入值的各种例子。
Working DEMO
演示工作
<select id="Ultra" onchange="run()"> <!--Call run() function-->
<option value="0">Select</option>
<option value="8">text1</option>
<option value="5">text2</option>
<option value="4">text3</option>
</select><br><br>
TextBox1<br>
<input type="text" id="srt" placeholder="get value on option select"><br>
TextBox2<br>
<input type="text" id="rtt" placeholder="Write Something !" onkeyup="up()">
The following script is getting the value of the selected option and putting it in text box 1
下面的脚本获取所选选项的值并将其放入文本框1中。
<script>
function run() {
document.getElementById("srt").value = document.getElementById("Ultra").value;
}
</script>
The following script is getting a value from a text box 2 and alerting with its value
下面的脚本从文本框2中获取一个值,并以其值警告。
<script>
function up() {
//if (document.getElementById("srt").value != "") {
var dop = document.getElementById("srt").value;
//}
alert(dop);
}
</script>
The following script is calling a function from a function
下面的脚本从函数调用函数。
<script>
function up() {
var dop = document.getElementById("srt").value;
pop(dop); // Calling function pop
}
function pop(val) {
alert(val);
}?
</script>
#5
20
var selectedValue = document.getElementById("ddlViewBy").value;
#6
18
If you ever run across code written purely for IE you might see this:
如果你遇到过纯粹为IE编写的代码,你可能会看到:
var e = document.getElementById("ddlViewBy");
var strUser = e.options(e.selectedIndex).value;
Running the above in Firefox et al will give you an 'is not a function' error because IE allows you to get away with using () instead of []:
在Firefox中运行上面的操作会给你一个“不是函数”的错误,因为IE允许你使用()而不是():
var e = document.getElementById("ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
The correct way is to use square brackets.
正确的方法是使用方括号。
#7
12
<select id="Ultra" onchange="alert(this.value)">
<option value="0">Select</option>
<option value="8">text1</option>
<option value="5">text2</option>
<option value="4">text3</option>
</select>
#8
11
Beginners are likely to want to access values from a select with the NAME attribute rather than ID attribute. We know all form elements need names, even before they get ids.
初学者很可能想要从一个带有NAME属性而不是ID属性的select中访问值。我们知道所有表单元素都需要名称,甚至在它们得到id之前。
So, I'm adding the getElementByName()
solution just for new developers to see too.
因此,我添加了getElementByName()解决方案,以便新开发人员也能看到。
NB. names for form elements will need to be unique for your form to be usable once posted, but the DOM can allow a name be shared by more than one element. For that reason consider adding IDs to forms if you can, or be explicit with form element names my_nth_select_named_x
and my_nth_text_input_named_y
.
NB。表单元素的名称将需要是唯一的,以使表单能够在发布时使用,但是DOM可以允许多个元素共享一个名称。由于这个原因,可以考虑添加id,如果可以,或者显式地使用表单元素名my_nth_select_named_x和my_nth_text_input_named_y。
Example using getElementByName
:
使用getElementByName示例:
var e = document.getElementByName("my_select_with_name_ddlViewBy");
var strUser = e.options[e.selectedIndex].value;
#9
10
Just use
只使用
-
$('#SelectBoxId option:selected').text();
for getting the text as listed$(' # SelectBoxId选项:选择')。text();以获取所列出的文本。
-
$('#SelectBoxId').val();
for getting the selected index value$(' # SelectBoxId ').val();获取所选索引值。
#10
7
The previous answers still leave room for improvement because of the possibilities, the intuitiveness of the code, and the use of id
versus name
. One can get a read-out of three data of a selected option -- its index number, its value and its text. This simple, cross-browser code does all three:
前面的答案仍然保留了改进的余地,因为有可能,代码的直观,以及id和名称的使用。我们可以得到一个选定选项的3个数据的读数——它的索引号、它的值和它的文本。这个简单的跨浏览器代码可以做到这三点:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo GetSelectOptionData</title>
</head>
<body>
<form name="demoForm">
<select name="demoSelect" onchange="showData()">
<option value="zilch">Select:</option>
<option value="A">Option 1</option>
<option value="B">Option 2</option>
<option value="C">Option 3</option>
</select>
</form>
<p id="firstP"> </p>
<p id="secondP"> </p>
<p id="thirdP"> </p>
<script>
function showData() {
var theSelect = demoForm.demoSelect;
var firstP = document.getElementById('firstP');
var secondP = document.getElementById('secondP');
var thirdP = document.getElementById('thirdP');
firstP.innerHTML = ('This option\'s index number is: ' + theSelect.selectedIndex + ' (Javascript index numbers start at 0)');
secondP.innerHTML = ('Its value is: ' + theSelect[theSelect.selectedIndex].value);
thirdP.innerHTML = ('Its text is: ' + theSelect[theSelect.selectedIndex].text);
}
</script>
</body>
</html>
Live demo: http://jsbin.com/jiwena/1/edit?html,output .
现场演示:http://jsbin.com/jiwena/1/edit?html输出。
id
should be used for make-up purposes. For functional form purposes, name
is still valid, also in HTML5, and should still be used. Lastly, mind the use square versus round brackets in certain places. As was explained before, only (older versions of) IE will accept round ones in all places.
id应该用于化妆。对于功能形式的目的,名称仍然有效,也在HTML5中,应该仍然使用。最后,注意在某些地方使用方括号和圆括号。正如之前所解释的那样,只有(较老版本的)IE会在所有地方接受圆形的。
#11
5
Refer to the article Selecting dropdown element using JavaScript or jQuery. They have explained it in many ways using JavaScript and jQuery.
请参阅使用JavaScript或jQuery选择dropdown元素的文章。他们在很多方面都用JavaScript和jQuery来解释。
Using jQuery:
使用jQuery:
$(‘select’).val();
#12
3
In 2015, in Firefox, the following also works.
在2015年,在Firefox中,下面的内容也可以使用。
e.options.selectedIndex
e.options.selectedIndex
#13
2
Here is a JavaScript code line:
下面是JavaScript代码行:
var x = document.form1.list.value;
Assuming that the dropdown menu named list name="list"
and included in a form with name attribute name="form1"
.
假设下拉菜单名为list name="list",并以name属性name="form1"的形式包含在表单中。
#14
2
To go along with the above answers, this is how I do it as a one-liner. This is for getting the actual text of the selected option. There are good examples for getting the index number already. (And for the text, I just wanted to show this way)
为了配合上面的答案,这是我作为一个一行人的方式。这是为了获取所选选项的实际文本。有很好的例子可以得到索引号。(对于文本,我只是想以这种方式展示)
var selText = document.getElementById('elementId').options[document.getElementById('elementId').selectedIndex].text
In some rare instances you may need to use parentheses, but this would be very rare.
在一些罕见的情况下,您可能需要使用括号,但这是非常罕见的。
var selText = (document.getElementById('elementId')).options[(document.getElementById('elementId')).selectedIndex].text;
I doubt this processes any faster than the two line version. I simply like to consolidate my code as much as possible.
我怀疑这个过程是否比这两行版本更快。我只是想尽可能地巩固我的代码。
If anyone knows how to do this in one line without having to get the element twice, I would love for you to comment and show me how. I haven't been able to figure that out yet...
如果有人知道如何在一行中做到这一点,而不需要两次得到这个元素,我希望你能对我进行评论,并告诉我该怎么做。我还没弄明白…
#15
2
Running example of how it works:
运行示例:
var e = document.getElementById("ddlViewBy");
var val1 = e.options[e.selectedIndex].value;
var txt = e.options[e.selectedIndex].text;
document.write("<br />Selected option Value: "+ val1);
document.write("<br />Selected option Text: "+ txt);
<select id="ddlViewBy">
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3" selected="selected">test3</option>
</select>
Note: The values don't change as the dropdown is changed, if you require that functionality then an onClick change is to be implemented.
注意:当下拉菜单被更改时,值不会改变,如果您需要这个功能,那么onClick更改将被实现。
#16
2
You can use querySelector
.
您可以使用querySelector。
E.g.
如。
var myElement = document.getElementById('ddlViewBy');
var myValue = myElement.querySelector('[selected]').value;
#17
1
The only reason I can see that makes this code not work is if you're using IE7-, and forgot to specify the value attribute for your <option>
-tags... Every other browser should convert what's inside open-close tags as the option value.
我能看到这个代码不工作的唯一原因是如果你使用IE7-,并且忘记为你的 <选项> -标签指定值属性…所有其他浏览器都应该将开放标签内的内容转换为选项值。
#18
-2
Here's an easy way to do it in an onchange function:
这里有一个简单的方法,在一个onchange函数中:
event.target.options[event.target.selectedIndex].dataset.name
event.target.options event.target.selectedIndex .dataset.name