Ad Code

Dynamic Table with Auto increment serial number on button click event

<html>
<head>
<script src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
<script>
$(document).ready(function() {
    var id = 0;
   
    // Add button functionality
    $("table.dynatable button.add").click(function() {
        id++;
        var master = $(this).parents("table.dynatable");
       
        // Get a new row based on the prototype row
        var prot = master.find(".prototype").clone();
        prot.attr("class", "")
        prot.find(".id1").attr("value", id);
        prot.find(".id1").attr("id", "id"+id);
        prot.find(".id2").attr("id", "name"+id);
        prot.find(".id3").attr("id", "mobile"+id);
        prot.find(".id4").attr("id", "email"+id);
       
        master.find("tbody").append(prot);
    });
   
    // Remove button functionality
    $("table.dynatable button.remove").on("click", function() {
        $(this).parents("tr").remove();
    });
});
</script>
<style>
    .dynatable {
        border: solid 1px #000;
        border-collapse: collapse;
    }
    .dynatable th,
    .dynatable td {
        border: solid 1px #000;
        padding: 2px 10px;
        width: 170px;
        text-align: center;
    }
    .dynatable .prototype {
        display:none;
    }
</style>
</head>
<body>
<table class="dynatable">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Mobile</th>
            <th><button class="add">Add</button></th>
        </tr>
    </thead>
        <tr class="prototype">
            <td><input type="text" name="id[]" id="id" value="0" class="id1" /></td>
            <td><input type="text" name="name[]" id="name" value="" class="id2"/></td>
            <td><input type="text" name="mobile[]" id="mobile" value="" class="id3"/></td>
            <td><input type="text" name="email[]" id="email" value="" class="id4"/></td>
            <td><button class="remove">Remove</button>
        </tr>
</table>
</body>
</html>

Post a Comment

0 Comments