Use of input array objects in ajax based forms where we want to give users open ended options to add unlimited number of items and then process them on form submission is very common now a days. As the input elements all have the same name and assuming no class or id attribute is available, validation can be a big pain in the back side.
The following code excerpt shows how to validate in such a scenario -
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content=
"HTML Tidy for Windows (vers 14 February 2006), see www.w3.org" />
<meta http-equiv="content-type" content=
"text/html; charset=us-ascii" />
<title>Hello World</title>
<script type="text/javascript" src=
"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript">
//<![CDATA[
function checkname(fieldname){
var field = document.getElementsByName(fieldname+"[]");
var status = 1;
for(i=0;i<field.length;i++){
if(status > 0){
if(field[i].value == ''){
status = 0;
}
}
}
if(status == 0){alert('The field can not be empty!');}
}
//]]>
</script>
</head>
<body>
<form method="post" action="" name="form" id="form">
<input type="text" name="faisal[]" value="" />
<input type="text" name="faisal[]" value="" />
<input type="text" name="faisal[]" value="" />
<input type="text" name="faisal[]" value="" />
<select name="ahmed[]">
<option value="">None</option>
<option value="1">1</option>
</select>
<input type="submit" value="test" onclick="checkname('ahmed');" />
</form>
</body>
</html>
Comments and queries are welcomed
thephpx
[ad code=1 align=center]