views:

112

answers:

3

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?
}
+1  A: 

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;
KennyTM
thanks this works. just curious: what happens if 'myForm' does not have a checkbox with the passed in checkboxName? Will it fail silently?
aeq
if `checkboxName` doesn't exist on form it will fail and throw a JS error. You should put some error checking in before setting the `checked` flag.
Wallace Breza
@aeq: It won't be silent. You could check with `var cb = document.forms['myForm'][checkboxName]; if (cb) { cb.checked=false; }`
KennyTM
A: 

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.

Sarfraz
That will look for a property named `formName` (literally) on the `document` object, not for the actual value that the variable has, you should use the bracket notation `document.forms[formName]` as KennyTM suggest.
CMS
@CMS: Updated for that, thanks :)
Sarfraz
@Sarfraz: You're welcome, the same applies to `checkName`, I would do: `document.forms[formName].elements[checkName].checked = status;`
CMS
@CMS: Yes updated with that before your comment, thanks again.
Sarfraz
A: 

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.

Wallace Breza