challengeAccepted
challengeAccepted

Reputation: 7590

Javascript to check a checkbox if an other checkbox is checked

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

Upvotes: 4

Views: 14243

Answers (3)

JohnFx
JohnFx

Reputation: 34909

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

Upvotes: 8

Eduardo
Eduardo

Reputation: 7841

For the first one:

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

For the second one:

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

Upvotes: 1

Ali Tarhini
Ali Tarhini

Reputation: 5358

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

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

Upvotes: 2

Related Questions