Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

checkbox

Status
Not open for further replies.

MartDawg

Programmer
Jan 14, 2004
33
US
I have one checkbox in a form

<input type='checkbox' name='sched' id='sched' value='60'>

my validate function is as follows

function validate() {
var size = form_1.sched.length;
//alert(size)
var returnval = false
for (i = 0; i < size; i++) {
if (form_1.sched.checked) {
returnval = true
}
}
if (returnval == false){
alert("Please make selection");
return false
}
}

This works fine, unless I have just one checkbox, size comes back as undefined? Why is that?
 
Because the way you've named your check boxes. Your input tag is: <input type='checkbox' name='sched' id='sched' value='60'> and your function is looking for check boxes that have numbers after the name: form_1.sched. Change the names to something like sched0, sched1, etc. and make sure the your for loop control (i in this case) starts with the first number: for (i = 0; i < size; i++)

There's always a better way. The fun is trying to find it!
 
Another ?

That makes sense, but, the way I have it now...

If I have more than one check box, it works fine, size returns the number of checkboxes. So if I have the following...


<input type='checkbox' name='sched' id='sched' value='60'>

<input type='checkbox' name='sched' id='sched' value='61'>

Size will return 2 and my loop works fine, it ONLY has a problem when their is one checkbox.
 
MartDawg,

this is because elements cannot be accessed via array notation until there are more than one by the same name.

you must check for the existence of the length property first:
Code:
function validate() {
	var size = form_1.sched.length;
	var returnval = false;

	if (!size) {
		if (form_1.sched.checked) {
			returnval = true;
		}
	}
	else {
		for (i = 0; i < size; i++) {
			if (form_1.sched[i].checked) {
				returnval = true;
			}
		}
		if (returnval == false){
			alert("Please make selection");
			return false;
		}
	}
}

=========================================================
-jeff
try { succeed(); } catch(E) { tryAgain(); }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top