I have a form that does 2 things:
- Pass a first name and email address to PHP.
- Dynamically add a new set of name/email fields on a click, in case the user wants to submit more than one or two sets of data.
Since I don't know exactly how many sets every user may choose to submit, I pass the data to PHP in an array (using a name followed by []), so I can use a foreach loop and always get every data set. Here is some code for better understanding:
<form method="post" action="submit.php" id="formID">
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="contacts">
<tr>
<td><label class="namelabel"><span>Friend's First Name:</span><input type="text" name="friendName[]" class="friendName" id="name1" /></label></td>
<td><label class="emaillabel"><span>Friend's Email:</span><input type="text" name="friendEmail[]" class="friendEmail" id="email1" /></label></td>
</tr>
</table>
<p class="addmore"><a href="#" id="addclick">Click Here To Send This To More Friends</a></p>
<input type="submit" value="Spread The News!" name="submit" />
</form>
<script language="javascript" type="text/javascript" src="include/jquery-1.3.2.min.js"></script>
<script language="javascript" type="text/javascript" src="include/jquery.validate.pack.js"></script>
<script type="text/javascript">
$(document).ready(function() {
fieldCount = 1;
$("#addclick").click(function(e){
e.preventDefault();
fieldCount+=1;
$('#contacts tr:last').after('<tr><td><label class="namelabel"><span>Friend\'s First Name:</span><input type="text" name="friendName[]" class="friendName" id="name' + fieldCount + '" /></label></td><td><label class="emaillabel"><span>Friend\'s Email:</span><input type="text" name="friendEmail[]" class="friendEmail" id="email' + fieldCount + '" /></label></td></tr>');
});
$("#formID").validate({
rules: {
"friendName[]": "required",
"friendEmail[]": "required email",
}
});
});
</script>
The problem is, however, that only the first friendName[] and friendEmail[] get validated on submission. You have to click on any other fields with the same name to get validation working (Like the lazy validation only kicks in after focus)
How can I use the same name for a form field, and get all of them validated at the same time?