简体   繁体   中英

How to make One button check Uncheck check box when clicked more than once?

I want to have one button that check unchecks a check box when clicked more than one time.

I came up with this:

 function choseall() {      
        switch (d) {

            case 1:
                document.getElementById('cbconditioning').checked = true
                document.getElementById('cbradio').checked = true
                break;
            case 2:
                document.getElementById('cbconditioning').checked = false
                document.getElementById('cbradio').checked = false
                break;
        }
    }


        <input id="btnchoseall" type="button" value="Chose All" onclick="choseall()" /></tr>
        <input id="cbradio" type="checkbox"/>b. TV Radio (TV, Home Theatre, etc.)</td>
        <input id="cbconditioning" type="checkbox"/>a. Air Conditioning</td>
function choseall(){
    var ischecked = document.getElementById('cbconditioning').checked;
    document.getElementById('cbconditioning').checked = !ischecked;
}

Flips the checked state of cbconditioning.

Incase if you have more than one checkbox, then using id is a wrong choose. Instead using name attribute

1) Get all the checkbox element with name cbconditioning using the following line.

var x = document.getElementsByName("cbconditioning");

2)Then using length property get the no.of checkboxes and iterate as follows

function choseall() {
    var x = document.getElementsByName("cbconditioning");
    for (var i = 0; i < x.length; i++) {
        if (document.getElementsByName("cbconditioning")[i].checked) {
            document.getElementsByName("cbconditioning")[i].checked = false;
        } else {
            document.getElementsByName("cbconditioning")[i].checked = true;
        }
    }
}

3) What you need is a toggle like functionality, which is taken care by the if...else.. statement.

4) There is no use of using switch in your function

JSFiddle

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