shimmy
shimmy

Reputation: 47

Uncheck a checkbox and another checkbox will untick

I have two checkboxes in a form. onclick if a checkbox called email is unchecked how can I get the other checkbox to also uncheck (if it is checked) ?

document.getElementById('email').onclick = function() {
     if (!this.checked) {
        !document.getElementById("other").checked;
    } else {
        // if not checked ...
    }
};

Am I completey barking up the wrong tree? Any help appriciated

Upvotes: 1

Views: 871

Answers (5)

Hemanthkumar
Hemanthkumar

Reputation: 1

This should help

function check() {
if(document.getElementById("email").checked){ 
    document.getElementById("other").checked = true;
}else{
    document.getElementById("other").checked = false;
}

}

HTML

<input type='checkbox' id='email' name='checkbox' onclick="check()" >email
<input type='checkbox' id='other' name='checkbox'>other

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

To synchronize the checking of the both at the same time you need just to use this.checked of the first clicked one on the checked attribute of the second one like :

document.getElementById("other").checked = this.checked;

NOTE : That will work on one way, what means the check will be synchronized just when you click on the first checkbox that you've attached the click event to.

document.getElementById('email').onclick = function() {
    document.getElementById("other").checked = this.checked;
};
<input id="email" type="checkbox" /> CHECKBOX 1
<br>
<input id="other" type="checkbox" /> CHECKBOX 2

Upvotes: 3

Emre Savcı
Emre Savcı

Reputation: 3080

You can make it like :

<form id="test" action="#" method="post">
    <div>
        <input type="checkbox" name="check" id="check"/>
    </div>

        <div>
        <input type="checkbox" name="check2" id="check2"/>
    </div>
</form>

document.getElementById('check').onclick = function() {

 if (!this.checked) {
    document.getElementById("check2").checked = false;
} else {

    // other logic ...
}};

Test it online on jsfiddle : https://jsfiddle.net/3dtq0w8x/

Upvotes: 0

Muhammad Usman
Muhammad Usman

Reputation: 10148

You can add event listener to email checkbox (which is a good practice) and then check if it is check or not and deal with the other checkbox according to that

For example

var ckb = document.getElementById('email')
ckb.addEventListener("click", function(e){
  if(!e.target.checked)
      document.getElementById('ot').checked = false;
})
<input type="checkbox" name="na" value="email" id="email">Email<br>
<input type="checkbox" name="na" value="other" id="ot">Other

Upvotes: 0

Reine Stenberg
Reine Stenberg

Reputation: 96

In your test code you are not setting the checked property of "other" to any value. You are just reading its value, then inverting it (with !).

You could try:

document.getElementById("other").checked = false;

Upvotes: 0

Related Questions