View Full Version : Dynamic textbox creation like on trackvia

07-12-2007, 08:18 PM
I am trying to make a php page that has a button that when clicked will generate html elements. What I am trying to do is very similar to trackvia.com but perhaps a bit simpler.

I have a form and then within the form I have the following javascript code to create an html element.

<script language="javascript">

function changeIt()
var i = 1;
my_div.innerHTML = my_div.innerHTML +
"<br>Block<input type='text' name='mytext'+ size='2'>Acres<input type='text' name='acres'+i size='4'>"


This part works, except that if I need to create multiple elements the values are dropped after clicking the button to create a second textbox when I try and POST the values after the form button (a different standard PHP form button.

Can anyone point me in the right direction?

07-13-2007, 12:30 PM
This is a Javascript question and should be moved to the javascript forum.

Your function has several things wrong with it;
"i" is never incremented so every time you call the function it will alwys be 1.
You aren't adding "i" to the variable name because I think you might be trying to use php syntax in javascript!
I don't think firefox likes you adding form elements in this way, hence you are seeing the values dropped (it works in IE7 though!). I don't advocate the use of innerHTML and always use DOM methods when adding elements to pages myself.

The simplist way to fix your script is this;

var i = 1; //define i outside the function so it is a global variable.
function changeIt()
var my_div=document.getElementById("my_div");

var newdiv = document.createElement("div");
newdiv.innerHTML = "<br>Block<input type='text' name='mytext"+i+"' size='2'>Acres<input type='text' name='acres"+i+"' size='4'>";
i++; //increment i after we've used it.

However I think you should learn about the DOM methods createElement, appendChild, etc and use these instead of innerHTML.

07-13-2007, 03:53 PM
Thank you so much for the help. I really appreciate it (especially the help with the code). I will look into all of this.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum