Add fields dynamically with Javascript / jQuery

September 1, 2017

See a live demo here.


<html>
<head>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <style>
    #header {
        border-bottom: 1px solid gray;
    }
    #template {
        display: none;
    }
    .row {
        padding: 5px;
    }
    .row > div {
        width: 200px;
        display: inline-block;
    }
    </style>
</head>
<body>

    <div id="container">
        <div id="header" class="row">
            <div>Row #</div>
            <div>First Name</div>
            <div>Last Name</div>
            <div></div>
        </div>
    </div>

    <div id="template" class="row">
        <div></div>
        <div><input type="text" name="first_name[]" value="" disabled="disabled" /></div>
        <div><input type="text" name="last_name[]" value="" disabled="disabled" /></div>
        <div><button class="delete">Delete</button></div>
    </div>

    <button id="add">Add</button>

    <script>
    $(function() {

        // "Add" button "click" handler
        $("#add").click(function() {
            var $container = $("#container");
            var $template = $("#template");

            // Add Row
            var $clone = $template.clone();
            $clone.removeAttr("id").css("display", "block");
            $clone.find("input").attr("disabled", false);
            $container.append($clone);

            // Row Number
            var num_rows = $container.children().length - 1;
            $clone.find("div:first").html("Row " + num_rows);
        });

        // Create a First Row
        $("#add").trigger("click");

        // Detect "click" on "container" div
        $("#container").click(function(e) {

            // Detect "click" on "Delete" button
            if ($(e.target).is(".delete")) {
                var $this = $(e.target);

                // Remove Row
                $this.parent().parent().remove();

                // Reset Row Numbers
                $("#container > .row").each(function(index) {
                    if (index > 0) {
                        $(this).find("div:first").html("Row " + index);
                    }
                });
            }

       });

    });
    </script>

</body>
</html>