Javascript jQuery 在更改时获取选定的下拉值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11991007/
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
jQuery get the selected dropdown value on change
提问by TMB87
I'm trying to get the value of a dropdown on change (and then change the values in a second dropdown).
我正在尝试获取更改下拉列表的值(然后更改第二个下拉列表中的值)。
EDIT:Thanks for all the replies, i've updated to add the () but the code is returning nothing, not null or undefined just a blank alert window
编辑:感谢所有回复,我已经更新添加了 () 但代码什么也没返回,不是 null 或 undefined 只是一个空白的警报窗口
However when I alert it out the attr(value) is undefined.
但是,当我提醒它时,attr(value) 是未定义的。
Any ideas on what i'm missing?
关于我缺少什么的任何想法?
Here is my code:
这是我的代码:
<script type="text/javascript">
$(document).ready(function() {
var roomID = "0"
$('.dropone').load('ajaxdropdown.aspx');
$('.droptwo').load('ajaxdropdown.aspx?drpType=room&roomid=' + roomID);
$('.dropone').change(function() {
var ts = new Date().getTime();
alert($(this).val)
$(".droptwo").empty();
$(".droptwo").load("ajaxdropdown.aspx?drpType=room&roomid=" + $(this).attr("value") + "&ts=" + ts);
});
});
</script>
回答by Shyju
val
is a method, not a property.
val
是一种方法,而不是一种属性。
use it like val()
像使用它一样 val()
If you are using it many places, i would assign it to a local variable and use it thereafter.
如果您在很多地方使用它,我会将它分配给一个局部变量,然后再使用它。
Also you can use the $.now()
function to get the unique time stamp. It is equal to DategetTime();
您也可以使用该$.now()
函数来获取唯一的时间戳。它等于 DategetTime();
$('.dropone').change(function() {
var item=$(this);
? ? alert(item.val())
$(".droptwo").empty();
? ? $(".droptwo").load("ajaxdropdown.aspx?drpType=room
&roomid=" +item.attr("value") + "&ts=" + $.now());
});
回答by thecodeparadox
$('.dropone').change(function() {
var val = $(this).val();
// OR
var val = this.value;
})
回答by jeff
You must obtain the value using a method, not a property. Use this:
您必须使用方法而不是属性来获取值。用这个:
alert($(this).val())
回答by Vlad
Add round brackets to your val: alert($(this).val())
将圆括号添加到您的 val: alert($(this).val())
回答by PodTech.io
You can also obtain custom attributes from the dropdown as below;
您还可以从下拉列表中获取自定义属性,如下所示;
$('.someclass').change (function () {
var val = this.value;
alert(val); //selected value
var element = $(this).find('option:selected'); // assign selected element
var myTag = element.attr("aTag"); // get attribute by name
alert(myTag);
});
<option name='somename' id='someid' aTag='123' value='XYZ'>XYZ</option>