我正在尝试创建一个名为“全部”的复选框,选中该复选框后,还会选中我表单中的其余复选框。我基本上没有 javascript 经验,如果这真的很基础,我很抱歉。我通过查看类似 this 的帖子将其拼凑在一起和 this .
<script type="text/javascript">
function checkIt(checkbox)
{
document.GetElementById("1").checked = true;
document.GetElementById("2").click();
}
</script>
我的 HTML 看起来像这样:
<form>
<input type="checkbox" id="A" onclick="checkIt(this)">All<br></input>
<input type="checkbox" id="1">One<br></input>
<input type="checkbox" id="2">Two<br></input>
</form>
当我选中复选框 All 时,如何让复选框 1 和 2 发生变化?谢谢。
由于您不熟悉 javascript,我建议您查看 jQuery javascript 库。许多编码人员发现它更易于学习/使用,而且毫无疑问它需要更少的输入。
Here are some introductory jQuery tutorials如果你好奇的话。
为了解决您的问题,我向您希望自动选中/取消选中的复选框添加了一个类,并使用该类来选中/取消选中复选框。
Working jsFiddle here
HTML:
<form>
<input type="checkbox" id="A">All<br></input>
<input type="checkbox" class="cb" id="1">One<br></input>
<input type="checkbox" class="cb" id="2">Two<br></input>
</form>
JQUERY:
$('#A').click(function() {
// alert($(this).prop('checked'));
if ($(this).is(':checked') == true) {
$('.cb').prop('checked', true);
}else{
$('.cb').prop('checked', false);
}
});
请注意,此解决方案使用 jQuery,因此您需要加载 jQuery 库(通常将此行放在您的 head 标记中):
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>