javascript:
//可以不选
function singleCheck(chk) {
$chk = $(chk);
var tempChecked = $chk[0].checked;
$chk.parent().parent().children(1, "input[type=checkbox]").each(function () {
$(this).children("input")[0].checked = false;
$chk[0].checked = tempChecked;
});
}
//必选一个
function singleOnlyCheck(chk) {
$chk = $(chk);
$chk.parent().parent().children(1, "input[type=checkbox]").each(function () {
$(this).children("input")[0].checked = false;
$chk[0].checked = true;
});
}
html:
<table border="1px">
<thead>
必选一个</thead>
<tr>
<td>
<input id="ckbAttendee112_am_1_" value="1" type="checkbox" onclick="singleOnlyCheck(this);" /><label
for="ckbAttendee112_am_1_">A</label>
</td>
<td>
<input id="ckbAttendee112_am_2_" type="checkbox" onclick="singleOnlyCheck(this);"
value="2" /><label for="ckbAttendee112_am_2_">A</label>
</td>
<td>
<input id="Checkbox5" value="1" type="checkbox" onclick="singleOnlyCheck(this);" /><label
for="ckbAttendee112_am_1_">A</label>
</td>
<td>
<input id="Checkbox6" type="checkbox" onclick="singleOnlyCheck(this);" value="2" /><label
for="ckbAttendee112_am_2_">A</label>
</td>
</tr>
</table>
<br />
<table border="1px">
<thead>
单选,但是可以不选</thead>
<tr>
<td>
<input id="Checkbox1" value="1" type="checkbox" onclick="singleCheck(this);" /><label
for="ckbAttendee112_am_1_">B</label>
</td>
<td>
<input id="Checkbox2" type="checkbox" onclick="singleCheck(this);" value="2" /><label
for="ckbAttendee112_am_2_">B</label>
</td>
<td>
<input id="Checkbox3" value="1" type="checkbox" onclick="singleCheck(this);" /><label
for="ckbAttendee112_am_1_">B</label>
</td>
<td>
<input id="Checkbox4" type="checkbox" onclick="singleCheck(this);" value="2" /><label
for="ckbAttendee112_am_2_">B</label>
</td>
</tr>
</table>
本文介绍了一种使用JavaScript和HTML实现单选复选框的方法。一种方式允许用户必须选择一个选项,而另一种则允许用户可以选择一个或完全不选。通过具体的代码示例和HTML结构展示了如何在网页上实现这些功能。
1235

被折叠的 条评论
为什么被折叠?



