Javascript to set a checkbox if another checkbox is checked

I have 2 checkboxes, consider chk1 and chk2. If one flag is set, the second flag should be checked automatically, and not vice versa. What should be javascript? Can anybody help me? Thank!

+3
source share
3 answers

Here is a simple built-in version to demonstrate the general idea. You might want to pull it into a separate function in the real world.

If you want chk2 to automatically stay in sync with any changes to chk1, but don't do anything when you click chk2, go ahead.

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

This version only changes chk2 if chk1 is checked, but does nothing if ck1 is not checked.

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

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

:

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

:

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

Source: https://habr.com/ru/post/1778189/


All Articles