jQuery

How to Add or Remove Table Rows Dynamically with jQuery

In this tutorial, we are going to see how to add or remove table rows dynamically with jQuery. You can use jQuery’s .append() method to add rows to an HTML table. In the same way, you can use the .remove() method to remove rows from an HTML table with jQuery.
 

HTML Code:
<html>
<head>
<style type="text/css">
      /* Put the CSS Style Here */
</style>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
      // Put the jQuery code Here 
</script>
</head>
<body>
    <input type="text" id="name" placeholder="Name">
    <input type="text" id="email" placeholder="Email address">
    <input type="button" class="add" value="Add row">
    <table class="test">
            <tr>
                <th>Select</th>
                <th>Name</th>
                <th>Email</th>
            </tr>
            <tr>
                <td><input type="checkbox" name="select"></td>
                <td>Thomas Babtise</td>
                <td>[email protected]</td>
            </tr>
    </table>
    <button type="button" class="delete">Delete row</button>
</body> 
</html>
 

jQuery Code:
$(document).ready(function() {
    $(".add").click(function() {
        var name = $("#name").val();
        var email = $("#email").val();
        var ligne = "<tr><td><input type='checkbox' name='select'></td><td>" + name + "</td><td>" + email + "</td></tr>";
        $("table.test").append(ligne);
    });
    $(".delete").click(function() {
        $("table.test").find('input[name="select"]').each(function() {
            if ($(this).is(":checked")) {
                $(this).parents("table.test tr").remove();
            }
        });
    });
});

 

CSS Code:
table {
    margin: 18px 0;
    width: 100%;
    border-collapse: collapse;
}
table th,
table td {
    text-align: left;
    padding: 6px;
}
table,
th,
td {
    border: 1px solid #000;
}
Result
Select Name Email
Thomas Babtise [email protected]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *