Add multiple rows to table dynamically in Javascri

2019-06-08 15:34发布

问题:

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>&nbsp;</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>

回答1:

So I got some help from someone at work. Here is what we got:

$(document).on('click', '#purchaseItems .add', function(){

        var row = $(this).closest('tr');
        var clone = row.clone();

        // clear the values
        var tr = clone.closest('tr');
        tr.find('input[type=text]').val('');

        $(this).closest('tr').after(clone);

    });

here is a live example in my first ever fiddle.

http://jsfiddle.net/paulscicluna/h5DV5/



回答2:

I agree jQuery is your friend for stuff like this. See this fiddle for an example

waaaaaay less code I managed to get the JS down to something like this:

var table = $("table"),
button = $("#clicktoadd");

 button.on('click', function() {
     table.append("<tr><td>New Data</td><td>New Data</td>");
   });

^^ cheers


edit:

I guess this is what you need:

var table = $("table");

$(document).on('click', 'a', function() {
   // some randomness to distinguish rows
   var a = Math.round( Math.random() * 10 ), b = Math.round( Math.random() * 10 );
   $(this).parents('tr').after("<tr><td>" + a + "</td><td>" + b + "</td><td><a           class='clicktoadd' href='#'>Click to Add</a></td>");
});

it has a slightly different html setup I've updated the fiddle above as well.