Suja Shyam
Suja Shyam

Reputation: 971

Deleting a row from dynamic html table using jquery

I have saved few data from the view to database and added it to dynamically created html table using jquery in my asp.net mvc application. The script is given below.

$(document).ready(function() {
    var attributetable = [];
    $("#AddAttrib").click(function(event) {
        event.preventDefault();
        $("#AttributeList").show();
        var attribute = $("#Attribute").val();
        var attributename = $("#Attribute option:selected").text();
        var documentId = $("#DocumentId").val();
        var instructionId = $("#InstructionId").val();

        var attributevalue = $("#text1").val();
        attributetable.push({
            attribute: attribute,
            attributevalue: attributevalue
        });
        var row = $("<tr></tr>");

        var contents = '<tr><td>' + attribute + '</td><td>' + attributename + '</td><td>' + attributevalue + '</td><td><a id="delete" href="#">Delete</a></td></tr>';
        $("#AttributeList").append(contents);

        var jsonToPost = {};
        jsonToPost.attribute = attribute;
        jsonToPost.attributename = attributename;
        jsonToPost.attributevalue = attributevalue;
        jsonToPost.documentId = documentId;
        jsonToPost.instructionId = instructionId;

        jsonToPostString = JSON.stringify(jsonToPost);
        alert(jsonToPostString);
        $.post("/Instruction/CreateInstnAttribute", { data: jsonToPostString });
    });

I need to delete the row when "delete" is clicked. The requirement is to delete the row on clicking the delete link. how can i achieve it? Thanks for all helps in prior.

Upvotes: 2

Views: 2734

Answers (1)

user113716
user113716

Reputation: 322462

It seems as though you are using the "delete" ID for more than one row. That is invalid. IDs must be unique. It should be a class instead.

<td><a class="delete" href="#">Delete</a></td>

Then if AttributeList is your <table>, you could place a .delegate() handler on it to handle clicks on the <a> elements that have the class "delete".

$("#AttributeList").delegate('a.delete', 'click', function( e ) {
    e.preventDefault();
    $(this).closest('tr').remove();
});

Place this inside your $(document).ready() call.

This uses .closest() to get its nearest <tr> ancestor, then .remove() to remove the row.

It also uses e.preventDefault() to disable the default behavior of the <a> element.

Upvotes: 4

Related Questions