Page 1 of 1

Javascript form validation

Posted: Tue Oct 14, 2003 4:51 pm
by penguinboy
Well, I have a form with dynamic checkboxes.
Before the user submits I want javascript to
check that at least one checkbox has been checked.
So far I havn't figured out a way to do this....


Here's some psudo-code that I've been working on...

Code: Select all

<html>
<head>
<title>Title</title>
<script type="text/javascript">
function valid()
&#123;
if(document.the_form.checkbox&#1111;].checked != true)
&#123;
alert("You must select at least one option to continue.")
return false;
&#125;
&#125;
</script>
</head>
<body>
<form name="the_form" method="post" action="" onsubmit="return valid();">
<table>
<tr><td><input type="submit" value="Create Record" /></td></tr>
<tr><td> </td></tr>
<tr>
<td>Check box 1</td>
<td><input type="checkbox" value="1" name="checkbox&#1111;]" /></td>
</tr>
<tr>
<td>Check box 2</td>
<td><input type="checkbox" value="2" name="checkbox&#1111;]" /></td>
</tr>
<tr>
<td>Check box 3</td>
<td><input type="checkbox" value="3" name="checkbox&#1111;]" /></td>
</tr>
</table>
</form>
</body>
</html>
Thanks for any help.

--pb

Posted: Tue Oct 14, 2003 7:14 pm
by microthick
I've fudged with your function a little to produce this:

Code: Select all

<script type="text/javascript">
function valid()
&#123;
	var i;
	var isValid = false;
	for (i = 0; i < document.the_form.checkbox.length; i++) &#123;
		if(document.the_form.checkbox&#1111;i].checked == true) &#123;
			isValid = true;
		&#125;
	&#125;
	if (!isValid) &#123;
		alert("You must select at least one option to continue.");
		return false;
	&#125;
&#125;
</script>
Note that for this to work I had to change the checkbox name to "checkbox" rather than "checkbox[]". I could not get this to work with "checkbox[]" as I think JavaScript then interprets it as a 2D array.

id

Posted: Tue Oct 14, 2003 7:28 pm
by phpScott
You need to use id's in your check box statements ie
<input type ="checkbox" name="checkbox[]" id = "selections">

then in your javascript you have to

Code: Select all

function someFunction()
&#123;
  cb = document.formName.selections
  found=false;
  x=0;
  while(x<cb.length; && !found)
  &#123;
     if(cb&#1111;x].value == "checked")
         found=true;
      x++;
  &#125;
  if(!found)
  &#123;
      alert('You must select at least one checkbox');
   &#125;
   else
   &#123;
       document.formName.submit();
    &#125;
&#125;

phpScott

Posted: Wed Oct 15, 2003 9:23 am
by penguinboy
Thanks for the help guys.

--pb