Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Loop through dyanamic form fields 1

Status
Not open for further replies.

tektipsismyfavorite

Technical User
May 4, 2006
57
US
I'm trying to write "user-added" fields to MySQL and can't figure out how to go about this.

The form has dynamically added fields and they're added in this method:
field2 <- starts at 2
field3
field4

When a field is added or removed from the page, i update a hidden input (visibleFields) with the values:
2,3,4,

Then I use this code when the form is processed:
Code:
$vParray = split(",",$_POST['visibleFields']);
	$total = count($vParray);

Now I'm not sure what to do and how to write this to the database. right now, my code is:
Code:
if($_POST['visibleFields'] != ""){
	for($i=2;$i <= $total+1; $i++){
		if($_POST['field'.$i] != ""){
			$insertSQL = sprintf("INSERT INTO mytable (field) VALUES (%s)",
				GetSQLValueString($_POST['field'.$i], "text"));
		}
		mysql_select_db($database, $connection);
		$Result = mysql_query($insertSQL, $connection) or die(mysql_error());
	}
}

Somehow I need to use the index of vParray rather than i to get the field number. Any ideas?
 
instead of naming all your dynamic fields field1 field2 etc name them "dynamicfield[]".

they will then be accessible to your php script in the array $_POST['dynamicfield'] (assuming you use the post method)
 
Ok, I tried this method out, and I must say it does work slightly better however I did run into an issue. See, when my fields are added to the page, I'm using the javascript "innerHTML" so it's actually writing it to the DOM.

When fields are subtracted, the only way I knew how to do this was to "hide" them by using "display: none;"

Well, the problem is even though they're hidden, they still go into the POST values.

Is there a way to get this to work using my old method, or do you suggest something else?
 
most browsers support the disabled property of form fields (see code example below). some browsers do not support this at all, but these are the lesser used variants like webtv etc

disabled fields are not sent to the server by the browser

the js to disable an element is straightforward:

Code:
document.getElementById("idofelement").disabled = true;

note that you will not be able to address a form element by name in javascript if it is called "something[]". i use id's instead.
 
yeah, i haven't changed that aspect of it. I just changed the names and the id's still all have 2,3,4 after the fieldname

I shall give this a try tonight. Thanks for the help!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top