简体   繁体   中英

javascript dynamic checkbox checking

I have a form (id="myForm") whose checkbox ("checkbox") I check/uncheck as follows:

document.forms['myForm'].checkbox.checked = false;

How can I do this dynamically? Ie have a function where I pass in the name of the checkbox and then check or uncheck it?

function check(name) {
  document.forms['myForm'].**name**.checked = false; // how can I do this right?
}

In Javascript, foo.bar is equivalent to foo["bar"] , thus you can use:

document.forms['myForm'][checkboxName].checked = false;

However, it is more direct if you can give each checkbox a unique id , and use

document.getElementById(checkboxId).checked = false;

You can create a simple function like this and pass in the ID of the checkbox and the resulting state whether or not the checkbox should be checked.

function checkTheBox(id, checkState)
{
    var checkbox = document.getElementById(id);
    if(checkbox) 
        checkbox.checked = checkState;
}

This sample also includes some error checking to ensure that the checkbox exists before attempting to set the checked flag.

尝试这个

document.forms['myForm'].**name**.defaultChecked = true;

Like this:

function checkuncheck(formName, checkName, status)
{
  document.forms[formName][checkName].checked = status;
}

Where you pass status as either true to make it checked or false to make it unchecked.

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