简体   繁体   中英

How to enable Javascript code with a checkbox?

I'm trying to enable a Javascript code only when I check a checkbox.

I want to insert a script so I can enable and disable the script by only checking or unchecking the box.

If you want the code to run only when the check box is checked, just wrap that code in a function, then check if that checkbox is checked at the top of said function. If it's not checked, return to stop the rest of the function from running.

function codeToRun() {

    var myCheckbox = document.getElementById("checkbox-id");

    if (!myCheckbox.checked) {
        return;
    }

    // Whatever code you want to be run
    doWhatYouWantToDoHere();
}

If the checkbox isn't checked, the function will return without running all the way through. If it is checked, the function will run normally.

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