最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript dynamic checkbox checking - Stack Overflow

programmeradmin0浏览0评论

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 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?
}

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 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?
}
Share asked Aug 17, 2010 at 14:56 aeqaeq 10.6k16 gold badges46 silver badges46 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

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)

  1. 暂无评论