我有一个包含多个复选框组的表单,每个复选框组都有一个相关的“全部”选项,单击该选项会取消选择所有相关的复选框。当检查任何相关的复选框时,该表格还需要取消选中“所有”选项。基本上,表单可以提交“全部”选项、任何相关选项或不提交选项。
选中任何复选框时,相关标签会变为粗体,包括“全部”选项。
我已经用jQuery编写了这种逻辑,但是,我似乎无法让一件能够正常工作 - 当检查了一个相关选项时,请删除“全部”选项。当用户单击相关选项之一时它会起作用,但它也会在刚刚选中后取消选中“全部”选项。
我想我的问题是,如何确定“源”事件是什么,以便确定是否运行那段代码?
带有“取消选择'全部'”的演示注释掉:http: //jsfiddle.net/8Ctvd/
JS:
$(function () {
$(".all").change(function () {
if ($(this).is(":checked")) $("input[rel='" + $(this).attr("rel") + "']:checked").not(".all").removeAttr("checked").change();
});
$("input[type='checkbox']").change(function (e) {
if ($(this).is(":checked")) $("label[for='" + $(this).attr("id") + "']").css("font-weight", "bold");
else {
$("label[for='" + $(this).attr("id") + "']").css("font-weight", "normal");
/* THIS UNCHECKS THE ALL EVERYTIME
if ($(this).not(".all"))
$("input.all[rel='" + $(this).attr("rel") + "']").removeAttr('checked').change();
*/
}
});
});
HTML:
<INPUT id=items_All class="checkbox all" name=items value=ALL type=checkbox rel="items">
<LABEL class="items checkbox-label" for=items_All>All</LABEL>
<INPUT id=items_1 class=checkbox name=items value=1 type=checkbox rel="items">
<LABEL class="items checkbox-label" for=items_1>Item 1</LABEL>
<INPUT id=items_2 class=checkbox name=items value=2 type=checkbox rel="items">
<LABEL class="items checkbox-label" for=items_2>Item 2</LABEL>
<INPUT id=items_3 class=checkbox name=items value=3 type=checkbox rel="items">
<LABEL class="items checkbox-label" for=items_3>Item 3</LABEL>
<br />
<INPUT id=widgets_All class="checkbox all" name=widgets value=ALL type=checkbox rel="widgets">
<LABEL class="widgets checkbox-label" for=widgets_All>All</LABEL>
<INPUT id=widgets_1 class=checkbox name=widgets value=1 type=checkbox rel="widgets">
<LABEL class="widgets checkbox-label" for=widgets_1>Widget 1</LABEL>
<INPUT id=widgets_2 class=checkbox name=widgets value=2 type=checkbox rel="widgets">
<LABEL class="widgets checkbox-label" for=widgets_2>Widget 2</LABEL>
<INPUT id=widgets_3 class=checkbox name=widgets value=3 type=checkbox rel="widgets">
<LABEL class="widgets checkbox-label" for=widgets_3>Widget 3</LABEL>