4

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

4
  • What do you mean by "not vice versa"? Commented Dec 2, 2010 at 21:01
  • 1
    I think he means that checking ck2 will not toggle chk1. 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. Commented Dec 2, 2010 at 21:13
  • @Jordan - I updated my answer so it addresses both cases. Commented Dec 2, 2010 at 21:19

3 Answers 3

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">
Sign up to request clarification or add additional context in comments.

2 Comments

Good answer since the onclick is important (onchange wouldn't trigger until focus is removed - thought it might be good to put both in case the user uses the space bar? Or does that trigger onclick?)
I did a quick test and the spacebar triggered it in Firefox and IE.
2
var chk1 = document.getElementById('chk1');
var chk2 = document.getElementById('chk2');

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

1 Comment

This solution will work if you don't want ck2 to UNCHECK when you uncheck ck1. It is a little unclear what the OP wants to happen (if anything) when you uncheck ck1.
1

For the first one:

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

For the second one:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.