使用jQuery更改下拉列表的选定值 [英] Change the selected value of a drop-down list with jQuery

查看:125
本文介绍了使用jQuery更改下拉列表的选定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含已知值的下拉列表。我想要做的是将下拉列表设置为我知道使用jQuery存在的特定值。使用常规JavaScript,我会做类似的事情:

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.

但是,我需要用jQuery做这个,因为我正在为我的选择器使用CSS类(愚蠢的 ASP.NET 客户端ID ...)。

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.

如何使用jQuery进行操作?

How can I do it with jQuery?

更新

事实证明,我第一次做对了:

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

我不确定这是jQuery还是Internet Explorer 6的错误(我猜的是Internet Explorer 6),但它非常烦人。

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的文档声明:


[jQuery.val]检查或 选择 ,所有单选按钮,复选框,并选择与该组值匹配的选项。

[jQuery.val] checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.

此行为在 jQuery 版本 1.2 及以上。

你最有可能想要这个:

$("._statusDDL").val('2');

这篇关于使用jQuery更改下拉列表的选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆