[javascript] jQuery append and remove dynamic table row

I can add many rows for a table, but I can't remove many rows. I only can remove 1 row per sequential add.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#addCF").click(function(){
        $("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" id="remCF">Remove</a></td></tr>');
        $("#remCF").on('click',function(){
            $(this).parent().parent().remove();
        });
    });
});
</script>

<table class="form-table" id="customFields">
<tr valign="top">
    <th scope="row"><label for="customFieldName">Custom Field</label></th>
    <td>
        <input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp;
        <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp;
        <a href="javascript:void(0);" id="addCF">Add</a>
    </td>
</tr>
</table>

You can see the code at http://jsfiddle.net/3AJcj/

I need help.

This question is related to javascript jquery html-table tablerow dom-traversal

The answer is


<script>
    $(document).ready(function(){
        var add = '<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td>';
        add+= '<input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" />&nbsp;&nbsp;&nbsp;';
        add+= '<input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" />&nbsp;';
        add+= '<a href="javascript:void(0);" class="remCF">Remove</a></td></tr>';

        $(".addCF").click(function(){ $("#customFields").append(add); });

        $("#customFields").on('click','.remCF',function(){
            var inx = $('.remCF').index(this);
            $('tr').eq(inx+1).remove();
        });
    });
</script>

Change ID to class :

$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');

$(".remCF").on('click',function(){
            $(this).parent().parent().remove();
        });

http://jsfiddle.net/7BHDm/1/


live view Link Jsfiddle

vary simple way you can solve it ..... take a look my new collected code.

 $(document).ready(function(){
            $(".add-row").click(function(){
                var name = $("#name").val();
                var email = $("#email").val();
                var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td></tr>";
                $("table tbody").append(markup);
            });

            // Find and remove selected table rows
            $(".delete-row").click(function(){
                $("table tbody").find('input[name="record"]').each(function(){
                    if($(this).is(":checked")){
                        $(this).parents("tr").remove();
                    }
                });
            });
        });   

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".add-row").click(function() {_x000D_
    var name = $("#name").val();_x000D_
    var email = $("#email").val();_x000D_
    var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td></tr>";_x000D_
    $("table tbody").append(markup);_x000D_
  });_x000D_
_x000D_
  // Find and remove selected table rows_x000D_
  $(".delete-row").click(function() {_x000D_
    $("table tbody").find('input[name="record"]').each(function() {_x000D_
      if ($(this).is(":checked")) {_x000D_
        $(this).parents("tr").remove();_x000D_
      }_x000D_
    });_x000D_
  });_x000D_
});
_x000D_
form {_x000D_
  margin: 20px 0;_x000D_
}_x000D_
form input,_x000D_
button {_x000D_
  padding: 6px;_x000D_
  font-size: 18px;_x000D_
}_x000D_
table {_x000D_
  width: 100%;_x000D_
  margin-bottom: 20px;_x000D_
  border-collapse: collapse;_x000D_
  background: #fff;_x000D_
}_x000D_
table,_x000D_
th,_x000D_
td {_x000D_
  border: 1px solid #cdcdcd;_x000D_
}_x000D_
table th,_x000D_
table td {_x000D_
  padding: 10px;_x000D_
  text-align: left;_x000D_
}_x000D_
body {_x000D_
  background: #ccc;_x000D_
}_x000D_
.add-row,_x000D_
.delete-row {_x000D_
  font-size: 16px;_x000D_
  font-weight: 600;_x000D_
  padding: 8px 16px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form>_x000D_
  <input type="text" id="name" placeholder="Name">_x000D_
  <input type="text" id="email" placeholder="Email">_x000D_
  <input type="button" class="add-row" value="Add Row">_x000D_
</form>_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Select</th>_x000D_
      <th>Name</th>_x000D_
      <th>Email</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>_x000D_
        <input type="checkbox" name="record">_x000D_
      </td>_x000D_
      <td>Peter Parker</td>_x000D_
      <td>[email protected]</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
<button type="button" class="delete-row">Delete Row</button>
_x000D_
_x000D_
_x000D_


<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script>`enter code here`
        $(document).ready(function () {
var result=1;
$('input').keyup(function(){`enter code here`
     $('tr').each(function () {
         var sum = $(this).find('td.combat').text();
         var combat = $(this).find('input.combat').val();
         if (!isNaN(sum) && sum.length !== 0 && !isNaN(combat) && combat.length !== 0) {
                 result = parseFloat(sum)*parseFloat(combat);
             }

         $(this).find('.total-combat').html(result);
        });
    });
 $('.add').click(function(){
        var sno = $(this).parent().siblings('.sno').text();
        var cust = $(this).parent().siblings('.cust').text();
        var price = $(this).parent().siblings('td.combat').text();
        var rowValue = [];
        $(this).closest('tr').find("input").each(function() {
                  rowValue.push($(this).val());
                  return $(this).val(); 
                 });

         var rowValue1 = [];
        $(this).closest('tr').find("span").each(function() {
                  rowValue1.push($(this).text());
                  return $(this).val(); 
                 });

                    var markup = "<tr><td class='sno'>" + sno + "</td><td class='custname'>" + cust +"</td><td class='price'>" + price +"</td><td><input type='text' class='newtext' value="+ rowValue[0] +"></td><td class='total'>" + rowValue1[0] +"</td><td><input type='submit' class='update' value='upd'><input type='button' class='del' value='del'></td></tr>";



        var rightcol = $(this).closest('tr').find(".cust");
        var row_count =  $('.tbl1 tbody tr').length;
        alert(row_count);

        if (row_count == 0) {


                        $(".tbl1 tbody").append(markup);


        }
        else
        {
            var tes=0;
            $('.tbl1 tbody tr').each(function(){
                        var leftcol = $(this).find(".custname");

                            if(rightcol.html() == leftcol.html()) {
                                alert(leftcol.html()+"-----------------"+rightcol.html());
                                $(this).find('.sno').text(sno);
                                $(this).find('.custname').text(cust);
                                $(this).find('.price').text(price);
                                $(this).find('.newtext').val(rowValue[0]);
                                $(this).find('.total').text(rowValue1[0]);
                                tes++;
                     }
            });
                if(tes==0){
                    $(".tbl1 tbody").append(markup);
                }    


        }

});
            $(".tb").on("click", ".update", function(e) {
                var rowValues = [];
                                    $(this).closest('tr').find("input").each(function() {
                                  rowValues.push($(this).val());
                                  return $(this).val(); 

                                 });
                    var total=$(this).closest('tr').find('.total').text();
                    var right_cols = $(this).closest('tr').find(".custname");

                $('.tbl tbody tr').each(function(){
                        var row = $(this);
                        var left_cols = $(this).find(".cust");
                            if(left_cols.html() == right_cols.html()) {

                                $(this).find('.text').val(rowValues[0]);
                                $(this).find('.total-combat').text(total);
                             }
                         });



        });         
                $(".tb").on("keyup", "input", function() {
                 $('tr').each(function () {
                     var sum = $(this).find('td.price').text();
                     var combat = $(this).find('input.newtext').val();
                     if (!isNaN(sum) && sum.length !== 0 && !isNaN(combat) && combat.length !== 0) {
                            result = parseFloat(sum)*parseFloat(combat);
                         }

                        $(this).find('.total').html(result);
                    });
                });
         $(".tb").on("click", ".del", function() {
                  $(this).closest('tr').remove();
              });
});


    </script>
<style>

    .table_style {
    width: 500px;
    margin: 0px auto;
    }
    table{
    width: 100%;
    border-collapse: collapse;
    }
    table tr td{
    width: 50%;
    border: 5px solid #ff751a;
    padding: 5px;
    }
    table tr th{
    border: 5px solid #79ff4d;
    padding: 5px;
    }
    input{
        width:35px;
    }
    .tbl1{
        margin-top: 50px;
        border: 0px solid #cdcdcd;
    }
    .btn{
        float:left;
    }
    </style>
        <title>E-Commerce-Table</title>
</head>
<body>

<div class="table_style">
    <caption>Price-List</caption>
<table class="tbl">
    <tr>
        <th>S.No</th>
        <th>P.Name</th>
        <th>Price</th>
        <th>Qnty</th>
        <th>Rate</th>   
        <th>action</th>
    </tr>
    <tbody>
    <tr>
        <td class="sno">1</td>
        <td class="cust">A</td>
        <td class="combat">5</td>
        <td class="tester"><input type="number" id="qnty1" name="Qnty" value="0" class="combat text"></td>
        <td><span class="total-combat"></span></td>
        <td><input type="submit" name="submit" value="Add" class="add"></td>
    </tr>
    <tr>
        <td class="sno">2</td>
        <td class="cust">B</td>
        <td class="combat">8</td>
        <td><input type="number" id="qnty2" name="Qnty" value="0" class="combat text"></td>
        <td><span class="total-combat"></span></td>
        <td><input type="submit" name="submit" value="Add" class="add"></td>
    </tr>
    <tr>
        <td class="sno">3</td>
        <td class="cust">C</td>
        <td class="combat">7</td>
        <td><input type="number" id="qnty3" name="Qnty" value="0" class="combat text"></td>
        <td><span class="total-combat"></span></td>
        <td><input type="submit" name="submit" value="Add" class="add"></td>
    </tr>
    <tr>
        <td class="sno">4</td>
        <td class="cust">D</td>
        <td class="combat">2</td>
        <td><input type="number" id="qnty4" name="Qnty" value="0" class="combat text"></td>
        <td><span class="total-combat"></span></td>
        <td><input type="submit" name="submit" value="Add" class="add"></td>
    </tr>
</tbody>

</table>

     <table class="tbl1">
        <thead>
            <tr>
                <th>S.No</th>
                <th>P.Name</th>
                <th>Price</th>
                <th>Qnty</th>
                <th>Rate</th>
                <th>action</th>
            </tr>
        </thead>
        <tbody class="tb">

        </tbody>
    </table>
    <button type="submit" name="addtocart" id="btn">Add-to-cart</button>
</div>

</body>
</html>

You can dynamically add and delete table rows like this in the image using jQuery.. enter image description here

Here is html part...

<form id='students' method='post' name='students' action='index.php'>

    <table border="1" cellspacing="0">
      <tr>
        <th><input class='check_all' type='checkbox' onclick="select_all()"/></th>
        <th>S. No</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Tamil</th>
        <th>English</th>
        <th>Computer</th>
        <th>Total</th>
      </tr>
      <tr>
        <td><input type='checkbox' class='case'/></td>
        <td>1.</td>
        <td><input type='text' id='first_name' name='first_name[]'/></td>
        <td><input type='text' id='last_name' name='last_name[]'/></td>
        <td><input type='text' id='tamil' name='tamil[]'/></td>
        <td><input type='text' id='english' name='english[]'/> </td>
        <td><input type='text' id='computer' name='computer[]'/></td>
        <td><input type='text' id='total' name='total[]'/> </td>
      </tr>
    </table>

    <button type="button" class='delete'>- Delete</button>
    <button type="button" class='addmore'>+ Add More</button>
    <p>
    <input type='submit' name='submit' value='submit' class='but'/></p>
</form>

Next need to include jquery...

<script src='jquery-1.9.1.min.js'></script>

Finally script which adds the table rows...

<script>
  var i=2;
  $(".addmore").on('click',function(){
    var data="<tr><td><input type='checkbox' class='case'/></td><td>"+i+".</td>";
        data +="<td><input type='text' id='first_name"+i+"' name='first_name[]'/></td> <td><input type='text' id='last_name"+i+"' name='last_name[]'/></td><td><input type='text' id='tamil"+i+"' name='tamil[]'/></td><td><input type='text' id='english"+i+"' name='english[]'/></td><td><input type='text' id='computer"+i+"' name='computer[]'/></td><td><input type='text' id='total"+i+"' name='total[]'/></td></tr>";
        $('table').append(data);
        i++;
});
</script>

Also refer demo & tutorial for this dynamically add & remove table rows


Please try that:

<script>
$(document).ready(function(){
    var add = '<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td>';
                add+= '<input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" />&nbsp;&nbsp;&nbsp;';
                add+= '<input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" />&nbsp;';
                add+= '<a href="javascript:void(0);" class="remCF">Remove</a></td></tr>';

    $(".addCF").click(function(){ $("#customFields").append(add); });

    $("#customFields").on('click','.remCF',function(){
        var inx = $('.remCF').index(this);
        $('tr').eq(inx+1).remove();
    });
});
</script>

There are multiple problems here

  1. Id should be unique in a page
  2. For dynamic elements, you need to use event delegation using .on()

Ex

$(document).ready(function(){
    $("#addCF").click(function(){
        $("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" id="remCF">Remove</a></td></tr>');
    });

    $("#customFields").on('click', '#remCF', function(){
        $(this).parent().parent().remove();
    });

});

Demo: Fiddle

See this demo where id properties are removed.

$(document).ready(function(){
    $("#addCF").click(function(){
        $("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" name="customFieldName[]" value="" placeholder="Input Name" /> &nbsp; <input type="text" class="code" name="customFieldValue[]" value="" placeholder="Input Value" /> &nbsp; <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
    });

    $("#customFields").on('click', '.remCF', function(){
        $(this).parent().parent().remove();
    });

});

$(document).ready(function () {
    Addrow();
})
$("#add").click(function () {
    Addrow();
})
rowcount = $("#tbuser td").closest.length;
function Addrow() {
    rowcount++;
    debugger
    var markup = "<tr><td></td><td><input type='text' name='stuclass' id='stuclass'/></td><td><select name='Institute' class='Institute_" + rowcount + "'></select></td><td><input type='text' name='obtmark' id='obtmark'/></td><td><input type='text' name='totalmark' id='totalmark'/></td><td><input type='text' name='per' id='per'/></td><td><button type='button' id='delete' onclick='deleterow(this);'>DELETE</button></td></tr>";
    $(".tbuser tbody").append(markup);

    $.ajax({
        type: 'GET',
        url: '@Url.Action("bindinst", "Home")',
        data: '',
        dataType: "json",
        success: function (data) {
            debugger;
            $(".Institute_" + rowcount).empty();
            $(".Institute_" + rowcount).append('<option Value="">--Select--</option>');
            $.each(data, function (i, result) {

                $(".Institute_" + rowcount).append('<option Value="' + result.Value + '">' + result.Text + '</option>');
            });
        },

    });


}

In addition to the other answers, I'd like to improve the removal, to something more generic:

$(this).closest('tr').remove();

This would be much better than using $(this).parent().parent().remove();, because it doesn't depend on the depth of the element. So, the structure of the row becomes much more flexible.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html-table

Table column sizing DataTables: Cannot read property 'length' of undefined TypeError: a bytes-like object is required, not 'str' in python and CSV How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3? Sorting table rows according to table header column using javascript or jquery How to make background of table cell transparent How to auto adjust table td width from the content bootstrap responsive table content wrapping How to print table using Javascript?

Examples related to tablerow

jQuery append and remove dynamic table row Live search through table rows How to show multiline text in a table cell jQuery each loop in table row jQuery: get parent tr for selected radio button

Examples related to dom-traversal

jQuery append and remove dynamic table row Jquery find nearest matching element How to select a single child element using jQuery?