...

View Full Version : how to for-loop php array ($_POST) elements correctly in js



mondsteigen
01-16-2012, 01:32 AM
I wrote js functions to reset a php form (multiple questions). The below works:


function resetForm(){
resetGroup(document.forms[0].answer1);
resetGroup(document.forms[0].answer2);
}

Answer1 and answer2 are the elements of $_POST array. (<input name="answer1"> in php). In this example, I tried with only two questions, but I have up to 35 questions in one form. Instead of writing the above resetGroup() 35 times, I want to for-loop it. I tried


function resetForm(){
for (var i=1; i<3; i++){
resetGroup(document.forms[0]."answer"+i);
}

That didn't work. Could someone help me to make the loop work? Or would someone have better or simpler idea? Thanks.

DaveyErwin
01-16-2012, 01:42 AM
resetGroup(document.forms[0]["answer"+i]);

mondsteigen
01-16-2012, 02:20 AM
resetGroup(document.forms[0].["answer"+i]); doesn't work :(

Old Pedant
01-16-2012, 02:24 AM
Read again what Davey wrote. You didn't copy his code. You added an extra unwanted period.

Personally, I'd avoid the repetitive references and do this:


function resetForm()
{
var form = document.forms[0];
for (var i=1; i<3; i++)
{
resetGroup(form["answer"+i]);
}
}

mondsteigen
01-16-2012, 04:20 AM
Thanks, Old Pedant. Davey's code didn't work, so I tried it with a dot (.). But I just realized that I missed the last '}' when I tried Davey's. Sorry Davey.

Old Pedant
01-16-2012, 04:29 AM
Actually, another simple trick to use is this one:


function resetForm()
{
var form = document.forms[0];
for (var i=1; i < 1000000; i++)
{
var fld = form["answer"+i];
if ( fld == null ) return;
resetGroup( fld );
}
}

Now you don't need to know ahead of time how many "answerXX" fields there are. The loop stops after the last one found.

mondsteigen
01-16-2012, 04:43 AM
I just saw the light. Thanks Old Pedant!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum