Why select/deselect checkbox works only once with jQuery?

谁说我不能喝 提交于 2019-12-13 18:10:50

问题


I've a simple Select/Deselect option to check and uncheck checkboxes in my page. It works well, but only once. I don't know what's the problem for!
Please take a look at my codes. You can see its demo here.

HTML codes:

<input type="checkbox" id="main" />Select All<br />
<input type="checkbox" class="options" />Item 1<br />
<input type="checkbox" class="options" />Item 2<br />
<input type="checkbox" class="options" />Item 3<br />
<input type="checkbox" class="options" />Item 4<br />

jQuery code:

$('#main').click(function(e) {
    $('.options').attr('checked', this.checked);
});

回答1:


You need to use .prop() instead of .attr()

Use

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

A Good Read .prop() vs .attr()



来源:https://stackoverflow.com/questions/24910549/why-select-deselect-checkbox-works-only-once-with-jquery

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