Welcome to WebmasterWorld Guest from 54.226.46.6

Forum Moderators: open

Message Too Old, No Replies

Newbie - help needed

Building an array from a form

     

Tourex

6:43 pm on Oct 2, 2007 (gmt 0)

10+ Year Member



Hi

I wonder if somebody could help a total JavaScript newbie.

I want to use JavaScript to validate a form and give an error message if the user doesn't select at least one checkbox in a range.

The trouble is that the form is written from a PHP script and the number of checkboxes vary. Each checkbox has an incremental name - "line1", "line2", "line3", etc. There is also a hidden field "lines" which indicates the total number of lines.

I can't figure how to transfer the field names "line1", etc into an array before checking whether any are ticked.

Any help would be VERY much appreciated.

Thanks

birdbrain

11:24 am on Oct 3, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there Tourex,

does this help, in some small way. ;)


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script type="text/javascript">
var df;
count=0;
window.onload=function(){
df=document.forms[0];
df.onsubmit=function(){
return checkForCheck();
}
}
function checkForCheck(){
inp=df.getElementsByTagName('input');
for(c=0;c<inp.length;c++) {
if((inp[c].type=='checkbox')&&(inp[c].checked==true)){
count++;
}
}
if(count==0) {
alert('please tick at least one checkbox');
return false;
}
else {
count=0;
return true;
}
}
</script>

</head>
<body>

<form action="#" >
<div>
<input name="line1" type="checkbox"/>
<input name="line2" type="checkbox"/>
<input name="line3" type="checkbox"/>
<input name="line4" type="checkbox"/>
<input name="line5" type="checkbox"/>
<input name="line6" type="checkbox"/>
<input type="submit" value="submit"/>
</div>
</form>

</body>
</html>

birdbrain

Tourex

11:53 am on Oct 3, 2007 (gmt 0)

10+ Year Member



Birdbrain - thanks a ton. That's exactly what I need. Now I can study that code and get it into my thick skull.

birdbrain

12:12 pm on Oct 3, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



No problem, you're very welcome. ;)
 

Featured Threads

Hot Threads This Week

Hot Threads This Month