Looping through populated textfields

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
taha
Forum Newbie
Posts: 17
Joined: Tue Nov 22, 2005 2:40 pm

Looping through populated textfields

Post 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.
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post 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.
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post 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
}
Post Reply