简体   繁体   中英

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

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 

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;

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/

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 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM