【发布时间】:2015-06-09 12:27:48
【问题描述】:
我必须在我的项目中使用一组复选框。
这就是我的 HTML 的样子:
<label class="checkbox-inline">
<input type="checkbox" name="hairColor" value="1"> hairColor-1
</label>
<label class="checkbox-inline">
<input type="checkbox" name="hairColor" value="2"> hairColor-2
</label>
<label class="checkbox-inline">
<input type="checkbox" name="hairColor" value="3"> hairColor-3
</label>
<label class="checkbox-inline">
<input type="checkbox" name="hairColor" value="4" class="any"> any
</label>
<br>
<label class="checkbox-inline">
<input type="checkbox" name="eyeColor" value="1"> eyeColor-1
</label>
<label class="checkbox-inline">
<input type="checkbox" name="eyeColor" value="2"> eyeColor-2
</label>
<label class="checkbox-inline">
<input type="checkbox" name="eyeColor" value="3"> eyeColor-3
</label>
<label class="checkbox-inline">
<input type="checkbox" name="eyeColor" value="4" class="any"> any
</label>
使用此复选框,用户可以选择他们喜欢的选项。但是,如果他们选择带有“任何”的复选框文本,我需要取消选中组内已经做出的所有其他选择。而且,如果他们选中该复选框,则不应选中其他复选框。
这就是我使用 Jquery 尝试的方式。
$( "body" ).on( "change", ".checkbox-inline > input[type=checkbox]", function() {
if ($(this).hasClass("any")) { //Any checkbox tick
if ($(this).prop("checked")) { //User checked any
//Other checkboxes are unchecked
$(".checkbox-inline > input[type=checkbox][name=" + $(this).attr("name") + "]:not(.any)").prop("checked", false)
}
} else { //Other checkbox tick
if ($(this).prop("checked")) {//User checked another checkbox
//Any checkbox is unchecked
$("[name=" + $(this).attr("name") + "].any").prop("checked", false);
}
}
});
它对我有用。但我的问题是,当我将 name 值更改为 array 类型时,如 hairColor[] 然后我的代码不起作用。
【问题讨论】:
-
自动拼写我假设:)
-
cmon Alex,这让我笑得很开心!
-
对不起,错字错误...这是在
array类型中与name一起工作 - jsfiddle.net/6D9kS/174
标签: javascript jquery checkbox