I am new in programming and
I have created a form.
I want to insert this elements in the table when I click the add button
I already know how to add label and textfield and I want to know how to add row and insert new label and textfield in the table
<SCRIPT type="text/javascript">
var x = 1;
function add(type) {
var newlabel = document.createElement("Label");
newlabel.for = "Name";
newlabel.innerHTML = "NAME: ";
var element = document.createElement("input");
element.setAttribute("type", type);
element.setAttribute("name", type);
element.setAttribute("value", "Name"+x);
element.setAttribute("id", "Name"+x);
element.setAttribute("style","width: 64");
var newlabel1 = document.createElement("Label");
newlabel1.for = "AGE";
newlabel1.innerHTML = "AGE: ";
var element1 = document.createElement("input");
element1.setAttribute("type", type);
element1.setAttribute("name", type);
element1.setAttribute("value", "AGE"+x);
element1.setAttribute("id", "AGE"+x);
element1.setAttribute("style","width: 64");
var foo = document.getElementById("fooBar");
foo.appendChild(newlabel);
foo.appendChild(element);
foo.appendChild(newlabel1);
foo.appendChild(element1);
x++;
}
</script>
<form id="fooBar" form name="form1" method="post" action="">
<table id = "mytable" table border="1">
<tr>
<th scope="col">name: </th>
<th scope="col">
<label for="name"></label>
<input type="text" name="name" id="name">
</th>
<th scope="col">age:</th>
<th scope="col">
<label for="name2"></label>
<input type="text" name="name2" id="name2">
</th>
</tr>
</table>
<INPUT type="button" value="Add" onClick="add('text')" style="width:100px;"/>
</form>
In your code:
The language attribute for script elements is deprecated, type is required, use:
…
The value of the for attribute must match the ID of a form control, otherwise it will not be associated with the control. Also, it is easier and more robust to set element properties rather that use setAttribute:
Note that the HTML for attribute is referenced as the htmlFor property because for is a reserved word in javascript (actually ECMAScript).
Rather than using the innerHTML property, you should probably be appending a text node:
Your HTML should look like:
Note that if you are using a BUTTON element, that what might be happening is that the form is being submitted (because button elements are, by default, submit buttons) so the fields are being added but because the form submits, you don’t see it. Make sure the button is type=”button”.