I want to be able to add as many rows as I like to a table so that it dynamically grows and shrinks. (Right now I'm just concentrating on it growing) This code works great when I want to add a row to the bottom of the table, however when I want to add a row in the middle of the table, there is something in my code not quite right, (and I get an error).
eg.
title | title | title |
1....| 1.... | 1.... | addBtn
a few mins later
title | title | title |
1....| 1....| 1....| addBtn
2....| 2....| 2....| addBtn <- i click on this
3....| 3....| 3....| addBtn
4....| 4....| 4....| addBtn
becoming...
title | title | title |
1....| 1....| 1....| addBtn
2....| 2....| 2....| addBtn <- i clicked on this
3....| 3....| 3....| addBtn <- it created this row
4....| 4....| 4....| addBtn <- this row used to be in place 3
5....| 5....| 5....| addBtn <- this row used to be in place 4
I am new to this, but I have spent a day trying to get this working; also looking at the clone feature which doesn't seem to work either for me. I've also never worked with input arrays so if this is not correct then what would you recommend?
<script>
function displayResult(j)
{
if (j <= document.getElementById("purchaseItems").rows.length) {
for (var i= document.getElementById("purchaseItems").rows.length; i>j ;i--) {
var elName = "addRow[" + i + "]";
var newName = "addRow[" + (i+1) + "]";
var newClick = "displayResult(" + (i+1) + ")";
var modEl = document.getElementsByName(elName);
modEl.setAttribute("onclick", newClick);
document.getElementsByName("addRow[" + i + "]").setAttribute('name', "addRow[" + (i+1) + "]");
}
}
var table=document.getElementById("purchaseItems");
var row=table.insertRow(j);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var cell3=row.insertCell(2);
var cell4=row.insertCell(3);
var cell5=row.insertCell(4);
cell1.innerHTML="<input type=text class='tbDescription' name='description[]' required/>";
cell2.innerHTML="<input type=text name='itemPrice[]' required />";
cell3.innerHTML="<input type=text name='itemquantity[]' required />";
cell4.innerHTML="<input type='text' name='lineTotal[]' readonly />";
cell5.innerHTML="<input type='button' name='addRow["+ j + "]' class='add' onclick=\"displayResult(" + (j+1) + ")\" value='+' />";
}
Here is the HTML
<table id= "purchaseItems" name="purchaseItems" align="center">
<tr>
<th>Description</th>
<th>price</th>
<th>quantity</th>
<th>Line Total</th>
<td> </td>
</tr>
<tr>
<td><input type="text" name="description[]" class="tbDescription" required /></td>
<td><input type="text" name="price[]" required /></td>
<td><input type="text" name="quantity[]" required /></td>
<td><input type="text" name="lineTotal[]" readonly /></td>
<td><input type="button" name="addRow[1]" onclick="displayResult(2)" class="add" value='+' /></td>
</tr>