使用 jQuery 更改下拉列表的选定值 [英] Change the selected value of a drop-down list with jQuery
问题描述
我有一个包含已知值的下拉列表.我想要做的是将下拉列表设置为我知道使用 jQuery 存在的特定值.使用常规的 JavaScript,我会做类似的事情:
ddl = document.getElementById("这里是元素的ID");ddl.value = 2;//2 也是我想设置的值.
但是,我需要使用 jQuery 来执行此操作,因为我为我的选择器使用了 CSS 类(愚蠢的 ASP.NET 客户端 ID...).
以下是我尝试过的一些方法:
$("._statusDDL").val(2);//没有找到 2 作为值.$("._statusDDL").children("option").val(2)//也失败了.
<块引用>
如何使用 jQuery 来实现?
<小时>
更新
事实证明,我第一次就做对了:
$("._statusDDL").val(2);
当我在它正上方放置一个警报时工作正常,但是当我删除警报并让它全速运行时,我收到错误
<块引用>无法设置选定的属性.无效索引
我不确定这是 jQuery 还是 Internet Explorer 6 的错误(我猜是 Internet Explorer 6),但它非常烦人.
jQuery 的文档状态:
<块引用>[jQuery.val] 检查或选择,所有单选按钮、复选框和与值集匹配的选择选项.
此行为出现在 jQuery
版本 1.2
及更高版本中.
你很可能想要这个:
$("._statusDDL").val('2');
I have a drop-down list with known values. What I'm trying to do is set the drop down list to a particular value that I know exists using jQuery. Using regular JavaScript, I would do something like:
ddl = document.getElementById("ID of element goes here");
ddl.value = 2; // 2 being the value I want to set it too.
However, I need to do this with jQuery, because I'm using a CSS class for my selector (stupid ASP.NET client ids...).
Here are a few things I've tried:
$("._statusDDL").val(2); // Doesn't find 2 as a value.
$("._statusDDL").children("option").val(2) // Also failed.
How can I do it with jQuery?
Update
So as it turns out, I had it right the first time with:
$("._statusDDL").val(2);
When I put an alert just above it works fine, but when I remove the alert and let it run at full speed, I get the error
Could not set the selected property. Invalid Index
I'm not sure if it's a bug with jQuery or Internet Explorer 6 (I'm guessing Internet Explorer 6), but it's terribly annoying.
jQuery's documentation states:
[jQuery.val] checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.
This behavior is in jQuery
versions 1.2
and above.
You most likely want this:
$("._statusDDL").val('2');
这篇关于使用 jQuery 更改下拉列表的选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!