2

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks patrick. but am getting this error when view is loading Microsoft JScript runtime error: Object doesn't support this property or method
@Suja - What version of jQuery are you using? The delegate method was introduced in version 1.4.2. You'll get that error if you're using an older version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.