The most appropriate way is to get the form field from the form elements collection.
For example:
function test(chkBox) {
...
}
function buttonHandler () {
var form = this.form;
test(form.elements['checkbox1']);
};
var form = document.getElementById('testform');
form.elements.testbutton.onclick = buttonHandler;
Let’s take look at a test page the demonstrates the problem.
You might be in for a heap of trouble then, because field names are allowed to be duplicated multiple times on the page.
For example, an email field in the sign in form at the top of the page, the email field in the registration form in the main part of the page, and the email field in the subscription part near the bottom are all completely valid identical names on one page.
Some tidying up that can occur is to remove the name attribute from the form. The name attribute should only be used on elements within a form that are intended to be submitted.
Another tidy-up is to remove the id attribute from the input field, because it’s a bad habit to scatter around id attributes when they’re not being used.
Also, do you see the duplication in the following?
Assigning myForm.elements[retrivedChekboxName] to a variable can help tidy that up.
var checkbox = myForm.elements[retrivedChekboxName];
if (checkbox.checked === false) {
checkbox.checked = true;
Notice also that the coercive equality has been replaced with the strict equality. It’s a bad habit to use the coercive one, as it has several unintended consequences.
Also, a space has been placed between the if keyword and the condition parenthesis. It’s when calling a function that you have no space between the function name and the parenthesis. With keywords you place a space between them to help improve the readability of the code.
Finally, we now have three separate var satements.
var retrivedChekboxName = 'checkbox1';
var myForm = document.getElementById('test');
var checkbox = myForm.elements[retrivedChekboxName];
Those really should be defined in just the one var statement instead, such as this:
var retrivedChekboxName = 'checkbox1',
myForm = document.getElementById('test'),
checkbox = myForm.elements[retrivedChekboxName];
Just one more question: how do you get <label> being tied to a field if you don’t put an id on that field? I thought that the for attr had a match with the id.
Now that IE6 is considered to be dead, you don’t have resign yourself to using explicit association. You have implicit association at your disposal where you wrap the label around the field itself as well.
<label>Username: <input name="username"></label>
The 1999 specifications for HTML 4.01 show a similar implicit association example.
My code wouldn’t work once I leave jsFiddle. I cam with a very simple version of what I’m trying to do. This works in jsFIddle, but the exact same version doesn’t work in firefox.