如何使用 jQuery 向 <select> 添加 disabled=disabled 属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6858677/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:29:01  来源:igfitidea点击:

How do i add disabled=disabled attribute to <select> using jQuery?

jqueryselect

提问by Ibrahim Azhar Armar

I have a html field.

我有一个 html 字段。

<select name="select-states" disabled="disabled"><option value="">Choose State &raquo;</option></select>

initially the field is disabled, i want to enable or disable it based on events. to enable it i am using the following jQuery which works fine.

最初该字段被禁用,我想根据事件启用或禁用它。为了启用它,我正在使用以下 jQuery,它工作正常。

$('select[name="select-states"]').removeAttr('disabled');

I want to re-enable it using jQuery, for which i tried using this which does not work.

我想使用 jQuery 重新启用它,为此我尝试使用它不起作用。

$('select[name="select-states"]').attr('disabled');

What am i missing? which is the correct syntax for this?

我错过了什么?哪个是正确的语法?

thank you

谢谢你

回答by Jon Gauthier

In your code, you provide only one parameter to .attr(). This indicates that the function should just return the value for the disabledattribute of that element.

在您的代码中,您只向.attr(). 这表明该函数应该只返回该disabled元素的属性值。

To set the disabledattribute, provide the attribute name (first parameter) along with a value (second parameter):

要设置disabled属性,请提供属性名称(第一个参数)和值(第二个参数)

$('select[name="select-states"]').attr('disabled', 'disabled');