Page 1 of 1

Looping through populated textfields

Posted: Tue Nov 22, 2005 3:02 pm
by taha
I have created an indefinite (n) number of textfields on my page. I need to loop through each one and retrieve the data that was input by the user and store them so that i can load them into the database.

The textfields are created in a loop that are named incrementally, description textfield and a part number textfield, as such:

descriptionTextfield1 partnumberTextfield1
descriptionTextfield2 partnumberTextfield2
descriptionTextfield3 partnumberTextfield3
descriptionTextfield4 partnumberTextfield4
descriptionTextfield5 partnumberTextfield5
descriptionTextfield6 partnumberTextfield6
.
.
.
descriptionTextfieldn partnumberTextfieldn

Is this code below correct...in that the textfields name will be referred to as textfield1, textfield2, etc..?

Code: Select all

document.getElementById("textfields").innerHTML += 'Item '+numItems+'   Description<INPUT TYPE="text" NAME="idescription '+numItems+'" >
Part Number <INPUT TYPE="text" NAME="ipartno '+numItems+'" VALUE=""  ONKEYDOWN="if (event.keyCode==9) { addNewItem(); }">';
If so, how do i go about looping through those textfields? I was thinking that maybe i will be needing an array...that way each element of the array will hold a description field and a part no field. Then when i need to load into the database i could loop through each array element and populate the database.

Please let me know if this would work correctly and how i would go about it.

Thanks in advance.

Posted: Tue Nov 22, 2005 4:54 pm
by hawleyjr
Try something like this:

Code: Select all

<?php
//untested
$field_name = 'idescription';

if(is_array($_POST)){

	foreach($_POST as $ak => $value){
	
		if(substr($ak,0,strlen($field_name)) == $field_name){
			//ENTER ITEM INTO DATABASE
		
		}
	
	}

}

?>
Edit: Changed substr function name.

Posted: Tue Nov 22, 2005 6:14 pm
by Burrito
I would create the textfields as arrays, then you won't have to loop over the entire $_POST[] array.

ex:

Code: Select all

<input type="text" name="descriptionTextField[]">
<input type="text" name="descriptionTextField[]">
<input type="text" name="descriptionTextField[]">
<input type="text" name="descriptionTextField[]">
<input type="text" name="descriptionTextField[]">
<input type="text" name="descriptionTextField[]">
then on your php side:

Code: Select all

foreach($_POST['descriptionTextField'] as $val)
{
   // do stuff
}