jQuery-设置属性值 [英] JQuery - Set Attribute value

查看:82
本文介绍了jQuery-设置属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循以下HTML,其中两个元素具有相同的名称

I have following HTML with two elements having the same name

<input type="hidden" name= "chk0" value="">
<input type="checkbox" name="chk0" value="true" disabled>

通过JQuery,我要设置启用复选框.所以,我正在使用类似这样的东西:

Through JQuery, I want to set the enable the checkbox. So, I am using something like this:

$('#chk0').attr("disabled",false);

但这不起作用.我假设JQuery正在与具有相同名称的两个元素混淆.不幸的是,我无法避免使用两个不同的名称,因为在发布表单时,我希望所有复选框都被发布(而不仅仅是选中的复选框).因此,我必须使用具有相同名称的hidden元素..回到问题所在,在上述情况下如何通过JQuery启用复选框?是否有一个attr的类型"参数,该属性会隐藏复选框?

But this doesn't work. I assume JQuery is getting confused with two elements having the same identical name. Unfortunatel, I cannot avoid using two different names because, when the form is posted, I want all the checkboxes to get posted (not just the ones that are checked). Hence I have to use hidden element with the same name.. So, back to the question, how can I enable the checkbox through JQuery in the above scenario? Is there a "type" parameter for attr which distingues hidden from checkbox?

谢谢

推荐答案

实际代码之前有一些东西.

Some things before the actual code..

用作选择器的哈希(#)用于ID,而不用于元素名称. 同样,disabled属性不是真假场景..如果它具有disabled属性,则表示它是真..您需要删除该属性而不将其设置为false. 还有一些表单选择器,用于识别表单中特定类型的项目.

the hash (#) you use as the selector is for IDs and not for names of elements. also the disabled attribute is not a true false scenario .. if it has disabled attribute it means that it is true .. you need to remove the attribute and not set it to false. Also there are the form selectors that identify specific types of items in a form ..

因此代码应为

$("input:checkbox[name='chk0']").removeAttr('disabled');


使答案最新


Bringing the answer up-to-date

您应该使用 .prop() 方法(从v1.6开始添加的 )

$("input:checkbox[name='chk0']").prop('disabled', false); // to enable the checkbox

$("input:checkbox[name='chk0']").prop('disabled', true); // to disable the checkbox

这篇关于jQuery-设置属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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