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

4 Answers 4

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;
Sign up to request clarification or add additional context in comments.

3 Comments

thanks this works. just curious: what happens if 'myForm' does not have a checkbox with the passed in checkboxName? Will it fail silently?
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.
@aeq: It won't be silent. You could check with var cb = document.forms['myForm'][checkboxName]; if (cb) { cb.checked=false; }
1

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.

Comments

0

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.

3 Comments

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.
You're welcome, the same applies to checkName, I would do: document.forms[formName].elements[checkName].checked = status;
@CMS: Yes updated with that before your comment, thanks again.
0

try this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.