开发者

javascript dynamic checkbox checking

开发者 https://www.devze.com 2023-01-12 10:45 出处:网络
I have a form (id=\"myForm\") whose checkbox (\"checkbox\") I check/uncheck as follows: document.forms[\'myForm\'].checkbox.checked = false;

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? I.e. have a function where I pass in the nam开发者_JAVA百科e 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.


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.


try this

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号