...

View Full Version : Iterating through form with dynamic names



deafdigit
12-14-2011, 03:13 PM
Hi everybody,


I have a php file with an almost-standard html form. The not-so-standard part is that the name-attributes of the form elements are dynamically generated as such:



<? for($i=0; $i<5; $i++) { ?>
<input type="text" name="field_<? echo $i; ?>" />
<? } ?>


Now I want to do some javascript validation on the fields, but I'm having a bit of trouble accessing the values of the fields. My current code is as follows:



var i = 0;
var num = <? echo $step1_sag_faktura_num; ?>;

for (i=0; i<num; i++){
window['file_' + i] = document.forms["nyisagform_step2"]["sag_fak_file_" + i].value;
}


But this doesn't seem to work. It gives no error message. It just validates true.

Can somebody tell me a way to do this? I'm no good at javascript and the code above is pieced together by bit I found on the internet.


Thanks in advance,
deafdigit

mvmacd
12-14-2011, 03:40 PM
Does $step1_sag_faktura_num equal 5?


Your form names are:

field_1
field_2
...etc

But in your javascript I see not one reference of "field," just "file". so how are you validating? :confused:


If you want some code to work with, try this:



<?
for($i=0; $i<5; $i++) {
?>
<input type="text" name="field_<? echo $i; ?>" id="field_<? echo $i; ?>" />
<? } ?>



i = 0;
var num = <? echo $step1_sag_faktura_num; ?>;

for (i=0; i<num; i++){
window['file_' + i] = document.getElementById('field_' + i).value;
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum