jQuery receiving checkbox status

家住魔仙堡 提交于 2019-12-22 08:07:53

问题


I'm changing checkbox status this way: $(this).attr("checked", 'checked');

After this I want to receive checkbox status, but I got this:

$(this).attr('checked'): "checked"
$(this).is(':checked'): false

How this can be?

P.S. Maybe I'm not correctly changing checkbox status via jQuery?


回答1:


The proper way is $(this).prop('checked') to return the boolean property instead of the attribute (which is a a string).

Using .prop() you can also set the checked state: $(this).prop('checked', true_or_false);

As you can see on http://jsfiddle.net/ThiefMaster/QR2fL/, .attr('checked') returns the initial value of the attribute - it does not changed when checking/unchecking the checkbox.




回答2:


You should not check the checkbox like this:

$(this).attr("checked", 'checked');

but like this

$(this).prop("checked", true);

To check if a checkbox is checked you can use:

$(this).prop('checked');

or

$(this).is(':checked');

which return a boolean proerty



来源:https://stackoverflow.com/questions/7645508/jquery-receiving-checkbox-status

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!