Javascript: find a checkbox

Hello,

Could you please help me debug the below code? :slight_smile:

I have a few input whose names I know. I want to make sure they’re checked.

function test(name) {
	var chkBox = document.getElementsByName(name);
		if(chkBox != "undefined"){
				if(chkBox.checked == false) {
					chkBox.checked = true;
				}
		}
}

Is getElementsByName reliable (cross-browser, fast?) or should I use getElementById?

Cheers.

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;

Thanks Paul,

It seems though that my test() function isn’t working properly… Is there a mistake in my code?

And also, what if there’s no way I can know the form id, but I still know which fields I should trigger?

I really want to thank you for your help. It’s awesome! I’m learning a lot.

:slight_smile:

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.

Ok, I followed your advice. Does that look goo dto you? It works, at least. :slight_smile:

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?

if(myForm.elements[retrivedChekboxName].checked == false) {
    myForm.elements[retrivedChekboxName].checked = true;

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];

After all of that it’s looking a lot better.

Yeah. Thank you so much. Great, great help.

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.

:slight_smile:

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.

Oh, great to know :slight_smile:

I’m running into a strange problem, though.

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.

Here’s the fiddle: http://jsfiddle.net/rhgiant/FKCcS/

And here is my .html page (as I said, loaded in FF). The error I get (fro Firebug) is that testForm is null.


<!doctype html>

<html lang="en">

	<head>
	
		<title>Js Test</title>
		
		<script>
			var testForm = document.getElementById("testForm");
			testForm.elements["testCheck"].checked=true;
		</script>


	</head>

	<body>
			
			<form action="#" id="testForm" method="post">

				<input type="checkbox" name="testCheck">

			</form>


	</body>

</html>



I have tried to find for about 2 hours what could go wrong, didn’t come up with anything… Maybe you can see what is wrong, Paul?

:slight_smile:

The fiddle code is wrapped in an onload event. You don’t have to do that though. Just move your script to the end of the body and you’ll be fine.

You’re the kind of person that makes me say the internet is a great invention!