javascript 根据其他表单的值更改复选框的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18258616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change value of checkbox based on value of other form
提问by taronish4
I'm trying to have a checkbox called 'All' that when checked, also checks the rest of the checkboxes in my form. I have basically no javascript experience so sorry if this is really basic. I patched this together from looking at posts like thisand this.
在选中,我正在尝试拥有一个名为“全部”的复选框,还检查了我的表单中的其余复选框。我基本上没有 javascript 经验所以很抱歉,如果这真的很基本。我通过查看像这样和这样的帖子把它拼凑在一起。
<script type="text/javascript">
function checkIt(checkbox)
{
document.GetElementById("1").checked = true;
document.GetElementById("2").click();
}
</script>
My HTML looks like this:
我的 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>
How can I get checkboxes 1 and 2 to change when I select checkbox All? Thanks.
当我选择复选框全部时,如何让复选框 1 和 2 发生变化?谢谢。
采纳答案by cssyphus
Since you are not familiar with javascript, I suggest looking into the jQuery javascript library. Many coders find it simpler to learn/use, and there is no debate that it requires MUCH less typing.
由于您不熟悉 javascript,我建议您查看 jQuery javascript 库。许多编码人员发现它更易于学习/使用,并且毫无疑问它需要更少的打字。
Here are some introductory jQuery tutorialsif you are curious.
如果您好奇,这里有一些介绍性的 jQuery 教程。
To solve your problem, I added a class to the checkboxes that you wish to automatically check/uncheck, and used that class to check/uncheck the boxes.
为了解决您的问题,我在您希望自动选中/取消选中的复选框中添加了一个类,并使用该类来选中/取消选中这些复选框。
HTML:
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);
}
});
Note that this solution uses jQuery, so you need the jQuery library loaded (usually put this line in your head tags):
请注意,此解决方案使用 jQuery,因此您需要加载 jQuery 库(通常将此行放在您的 head 标签中):
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>