如果选中其他复选框,则使用 Javascript 选中复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4339721/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 11:05:09  来源:igfitidea点击:

Javascript to check a checkbox if an other checkbox is checked

javascripthtml

提问by Ram

I have 2 checkboxes, consider chk1 and chk2. If one checkbox is checked, the second checkbox should be checked automatically and not viceversa. What should be the javascript? Can someone help me? Thank you!!

我有 2 个复选框,考虑 chk1 和 chk2。如果选中一个复选框,则应自动选中第二个复选框,反之亦然。javascript 应该是什么?有人能帮我吗?谢谢!!

回答by JohnFx

Here's a simple inline version to demonstrate the general idea. You might want to pull it out into a separate function in real world usage.

这是一个简单的内联版本来演示总体思路。在实际使用中,您可能希望将其提取到一个单独的函数中。

If you want chk2 to automatically stay in sync with any changes to chk1, but not do anything when chk2 is clicked go with this.

如果您希望 chk2 自动与 chk1 的任何更改保持同步,但在单击 chk2 时不执行任何操作,请执行此操作。

 <input id="chk1" type="checkbox" onclick="document.getElementById('chk2').checked = this.checked;">
 <input id="chk2" type="checkbox">

This version will only change chk2 when chk1 is checked, but not do anything when ck1 is unchecked.

这个版本只会在 chk1 被选中时改变 chk2,而当 ck1 未被选中时不会做任何事情。

 <input id="chk1" type="checkbox" onclick="if (this.checked) document.getElementById('chk2').checked = true;">
 <input id="chk2" type="checkbox">

回答by Ali Tarhini

var chk1 = document.getElementById('chk1');
var chk2 = document.getElementById('chk2');

if ( chk1.checked )
      chk2.checked = true;

回答by Eduardo

For the first one:

对于第一个:

document.getElementById('chk1').checked = document.getElementById('chk2').checked;

For the second one:

对于第二个:

document.getElementById('chk2').checked = document.getElementById('chk1').checked;