最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Javascript to check a checkbox if an other checkbox is checked - Stack Overflow

programmeradmin4浏览0评论

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!!

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!!

Share Improve this question edited Dec 2, 2010 at 21:12 JohnFx 34.9k18 gold badges107 silver badges166 bronze badges asked Dec 2, 2010 at 20:51 challengeAcceptedchallengeAccepted 7,61020 gold badges79 silver badges113 bronze badges 4
  • What do you mean by "not vice versa"? – jordanbtucker Commented Dec 2, 2010 at 21:01
  • 1 I think he means that checking ck2 will not toggle chk1. – JohnFx Commented Dec 2, 2010 at 21:09
  • @John. That's what I figured, but it could mean he only wants chk2 to be checked automatically and never unchecked automatically. – jordanbtucker Commented Dec 2, 2010 at 21:13
  • @Jordan - I updated my answer so it addresses both cases. – JohnFx Commented Dec 2, 2010 at 21:19
Add a ment  | 

3 Answers 3

Reset to default 8

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.

 <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.

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

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

For the first one:

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

For the second one:

document.getElementById('chk2').checked = document.getElementById('chk1').checked;
发布评论

评论列表(0)

  1. 暂无评论