Forum Moderators: open

Message Too Old, No Replies

Javascript looping for PHP form

Need help fast

         

NLConsulting

3:54 pm on Apr 28, 2006 (gmt 0)

10+ Year Member



Here's the problem... I am trying to loop through a submitted form with Javascript to verify the information. The form has been created by PHP based on the number of attendees a user has selected, so if they say 1 person, the form pops up with an entry for 1 attendee. If they select 10 people, the form pops up with spots for 10 attendees. The textfield names are dynamically generated for this form based on the user selection as well (eg fist name field is fname1 for first attendee, fname2 for second attendee, etc). "att" is the hidden value of the number of people the user has selected when entering the form.

A snippet of code:

function Verify_Event(eventForm){
var msg="Processing your form produced the following errors:\n";
var errors=0;
for (i=1;i<=eventForm.att.value;i++) {
fnameA="fname"+i;
lnameA="lname"+i;
fname=eventForm.fnameA;
lname=eventForm.lnameA;
if (!fname.value ¦¦!lname.value) {
msg+="\n- Attendee #"+i+" - full name is required";
errors++;
}
}
if (errors!= 0) {
alert(msg);
return false;
}
}

You would call this function as such:
<input... onClick="return Verify_Event(this.form)">

So the problem is grabbing all of those dynamic values in a FOR loop. I'm not very stellar with JavaScript, so any suggestions will help.

NLConsulting

4:39 pm on Apr 28, 2006 (gmt 0)

10+ Year Member



Figures, after two days of Googling, I make a post and 30 minutes later I solve the problem. I'm going with Javascripts eval() to solve this one.

firstName=eval("eventForm.fname"+i);
lastName=eval("eventForm.lname"+i);
if (!firstName.value ¦¦!lastName.value) {
msg+="\n- Attendee #"+i+" - full name is required";
errors++;
}

islandlizard

7:12 pm on Apr 30, 2006 (gmt 0)

10+ Year Member



Just as an aside, you may be better having PHP generate the fieldnames to be an array, not a unique value. It makes it much quicker to process them after submission (and probably eaiser to build in the first place) i.e.


<?php
// presuming number to be added passed as variable $num

//start form
echo <<<OUT
<form action="process.php" method="post" onsubmit="validate('$num')" id="myform">
OUT;

$i=0;
while ($i < $num){
echo <<<ROW
Enter Person $num:
firstname:<br />
<input type="text" name="fname[]" />
lastname:<br />
<input type="text" name="lname[]" />
...
...
ROW;
$i++;
}
echo <<<END
<inpu type="submit" name="submit" value="Add People" />
</form>

END;
?>

then, to process the values, you can simply loop again with PHP:


<?php

$total=count($_POST['fname']);
$i=0
while ($i <=$total){

$this_fname=$_POST['fname'][$i];
$this_lname=$_POST['lname'][$i];

// add to DB as required

$i++
}
?>

Just an option to reduce the work involved in counting them all and sending additional data through the form

HIH