Problem creating new form elements using javascript
Posted: Sat Jul 25, 2009 5:38 pm
I am trying to write a script that inserts new input fields while the person is filling out a form. While I can do this, placement of the submit button is awkward as a result of trying to work around a bug.
This is the html that I would like to use, when inserting a new field, it would get added to the end of the current table of fields.
However, in order to get it to work I have to use this:
This puts the submit button at the top of the form, which I want to avoid.
Here is my javascript code
Btw, the resultant php code works as expected.
This is the html that I would like to use, when inserting a new field, it would get added to the end of the current table of fields.
Code: Select all
<form action="forming.php" name="form" id="form" method="post">
<table id="table">
<tr><td><a href="javascript:newField();">New Element</a></td></tr>
<tr><td><input type="text" name="name[]"></input></td></tr>
</table>
<input type="submit" value="Try!" />
</form>
Code: Select all
<table id="table">
<form action="forming.php" name="form" id="form" method="post">
<tr><td><input type="submit" value="Try!" />
<tr><td><a href="javascript:newField();">New Element</a></td></tr>
<tr><td><input type="text" name="name[]"></input></td></tr>
</form>
</table>
Here is my javascript code
Code: Select all
function newField()
{
var form=document.getElementById("form");
var tr=document.createElement('tr');
var td=document.createElement('td');
var input=document.createElement('input');
input.setAttribute("type", "text");
input.setAttribute("name", "name[]");
form.appendChild(tr);
tr.appendChild(td);
td.appendChild(input);
}