views:

891

answers:

3

i'm using this to generate a textbox dynamically:`

<html>
<head>
<title>Dynamic Form</title>
<script type="text/javascript" >
function CreateTextbox()
{
var i = 6;
createTextbox.innerHTML = createTextbox.innerHTML +"<input type=text name='flow'+ i/>"
i++;
}
</script>
</head>
<body>

<form name="form" action="post" method="">
<input type="button" value="clickHere" onClick="CreateTextbox()">
<div id="createTextbox"></div>
</form>
</body>

how can i get the value from the added textbox?

i'm using javascript and php.

+1  A: 

Add a generated ID to the textbox and use this ID to retrieve the input

function CreateTextbox()
{
  var i = 6;
  createTextbox.innerHTML = createTextbox.innerHTML +"<input type=text name='flow'+ i id='box'+i/>"
  i++;
}

function getBox(var id){
  return document.getElementById("box"+i);
}
marcgg
can you give a simple example on that? thanks.
noob
here you go. does that make sense?
marcgg
A: 

set name="flow[]" so you can get all values as an array just by using $_POST['flow']

w35l3y
A: 

createTextbox.innerHTML = createTextbox.innerHTML +"<input type=text name='flow'+ i/>"

Your quotes are in the wrong place, the '+i' actually is part of the literal string! What you meant was:

'<input type="text" name="flow'+i+'" />'

(also added quotes to the type attribute: if you're going to use XHTML syntax might as well do it properly.)

You'd then get form control names like 'flow6' sent to your script. A more usual way for PHP users would be to use an array, which you can persuade PHP to do by putting square brackets in the name:

'<input type="text" name="flow['+i+']" />'

You also seem to be missing a:

var createTextbox= document.getElementById('createTextbox');

Don't rely on IE's misbehaviour of turning named elements into global variables; it won't work elsewhere.

Anyhow, avoid appending to innerHTML. Every time you do it, everything inside createTextbox will be labouriously serialised into a stringful of HTML, then you alter the string and write it back, parsing it all back into objects. In the process you lose anything that couldn't be serialised to HTML, such as JavaScript references and event bindings.

If you can do a single write to innerHTML, or use DOM methods to create your elements, that's generally better.

bobince