Javascript 如何在客户端 onchange 事件中获取下拉选择值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9062628/
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 Dropdown selected value on client side onchange event?
提问by Atul Patel
I have written a code for dropdown selected index changed event at client side using onchange event and create one JavaScript function. Now, I want to retrieve selected values in this function. How can I get this value?
我已经使用 onchange 事件为客户端的下拉选择索引更改事件编写了代码,并创建了一个 JavaScript 函数。现在,我想在这个函数中检索选定的值。我怎样才能得到这个值?
回答by Anwar
$("#DropDownlist:selected").val();
回答by devson
This will give you selected text.
这将为您提供选定的文本。
$("#mydropdownid option:selected").text();
This will give you selected value
这将为您提供选定的值
$('#mydropdownid').val();
回答by Ariful Islam
HTML :
HTML :
<select id="mySelect" class="myClass">
<option value='1'>One</option>
</select>
jQuery :
jQuery :
Now for getting selected value you can use the one of the following:
现在要获取选定的值,您可以使用以下方法之一:
ONE :
一 :
var selected_value = $("#mySelect").val();
TWO :
二 :
var selected_value = $(".myClass").val();
THREE :
三 :
var dropdown = $("#mySelect option:selected");
var selected_value = dropdown.val();
回答by mpaf
The simplest, inside the event handler:
最简单的,在事件处理程序中:
$('#elementID').change(function(event) {
event.target.value;
};
event is the event object sent to the handler, target is the object in the DOM from which the event generated, and value it's the DOM element current value. In the case of a select box this will work perfectly to get your selected value.
event 是发送到处理程序的事件对象,target 是生成事件的 DOM 中的对象,value 是 DOM 元素的当前值。在选择框的情况下,这将完美地获得您选择的值。
回答by Nix
As you have tagged jQuery, I assume that's what you are using. Simply use jQuery val()
当您标记 jQuery 时,我认为这就是您正在使用的。只需使用 jQuery val()
var v = $("#yourSelectID").val();
alert("The value is: " + v);
You should also be able to use plain javascript:
您还应该能够使用普通的 javascript:
var e = document.getElementById("yourSelectID");
var v = e.options[e.selectedIndex].value;
alert("The value is: " + v);