I am trying to add a new row on button click. In my new row I am trying to add a Textbox and a dropdown list. I don't know what I am doing wrong ? Can anybody help me with this problem. Thanks in advance.
HTML
<table>
<tr>
<td><input type="text" name="data1" value="TempData" /></td>
<td><button type="button" onClick ="addRow(this)">Add</button></td>
</tr>
</table>
Javascript function:
function addRow(btn) {
var parentRow = btn.parentNode.parentNode;
var table = parentRow.parentNode;
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
cell1.appendChild(element1);
var cell3 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "select";
var option1 = document.createElement("option");
option1.innerHTML = "Option1";
option1.value = "1";
element2.add(option1, null);
var option2 = document.createElement("option");
option2.innerHTML = "Option2";
option2.value = "2";
element2.add(option2, null);
cell3.appendChild(element2);
}
JSFiddle http://jsfiddle.net/wAyhm/2/
Try this using jQuery. But if u want answer in javascript then skip my answer.
This kind of fixed your problem
Updated Fiddle:
Problem was with the commented lines. A
select
element isn't aninput
element. You can't have a<input type="select"/>
. Since anHTMLInputElement
doesn't have anadd
method,addRow
threw an exception.You can add any number of rows by following code