Editing and deleting a newly added table row using

2019-09-03 13:52发布

I'm adding new rows dynamically to the existing table, the first column of the table holds the Edit & Delete buttons. I'm facing 2 problems with this:

  1. Not able to Edit and Delete newly added rows, tried .live but couldn't make it work
  2. Not able to get the record id of the newly added rows (ajax returns the record when new rows are added).

Code looks like this:

Adding new rows:

 <script type="text/javascript">
     $(function() {
         $('#btnSubmit').click(function() {

             var oEmployee = new Object();

             oEmployee.Title        = $("#Title").val();
             oEmployee.Middlename   = $("#MiddleName").val();
             oEmployee.Lastname     = $("#LastName").val();
             oEmployee.Email        = $("#Email").val();

             var DTO =  {'employee': oEmployee};

             var options = {
                 type: "POST",
                 url: "WebService.asmx/InsertEmployee",
                 data: JSON.stringify(DTO),
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 success: function(response) {
                     if (response.d != "") {
                         if (parseInt(response.d) >= 1) {
                             var contactID;
                             contactID = parseInt(response.d);
                             $('#tblEmployee tbody tr:first').after("<tr id=" + contactID + "><td><input type='button' class='newContactID' value='Edit'/>&nbsp;<input type='button' value='Delete'/></td><td align=center>" + contactID + "</td><td align=center>" + oEmployee.Title + "</td><td align=center>" + oEmployee.Middlename + "</td><td align=center>" + oEmployee.Lastname + "</td><td align=center>" + oEmployee.Email + "</td><tr>"); // need to hook up editing and deleting function to the newly added rows  }
                         else {
                             alert("Insert Failed \n" + response.d);
                         }
                     }
                 }
             };
             //Call the webservice
             $.ajax(options);
         });
     });                          
</script>

Code for editing and deleting:

$(function() {
    $("#tblEmployee > tbody > tr ").each(function() {
        var TRID = $(this).attr("id");
        $(this).find("td:first > input[value=Edit]").click(function() {
            ResetOtherRowEdit();
            ChangeTableCellToTextbox(TRID);
            $(this).hide();
            $("#tblEmployee > tbody >  tr[id=" + TRID + "] > td:first> input[value=Delete]").hide();
            return false;
        });

        $(this).find("td:first > input[value=Update]").click(function() {
            UpdateRow(TRID);
        });

        $(this).find("td:first > input[value=Delete]").click(function() {
            DeleteRow(TRID);
        });

        $(this).find("td:first > input[value=Cancel]").click(function() {
            CancelEdit(TRID);
        });           
    });
});

What is the best way to approach this? Editing and deleting of records work fine when they're pulled off the database.


Update

This is how the code looks like now, just began dabbling with Jquery a month back, still trying to get my head around it.

    $(function() {
        $("#tblEmployee > tbody > tr ").live('click', function(e) {
            var TRID = $(this).attr("id");
            var $target = $(e.target);

            if ($target.is('#btnEdit')) {
                $(this).find("td:first > input[value=Edit]").click(function() {
                    ResetOtherRowEdit();
                    ChangeTableCellToTextbox(TRID);
                    $(this).hide();
                    $("#tblEmployee > tbody >  tr[id=" + TRID + "] > td:first> input[value=Delete]").hide();
                    return false;
                });
            }
            else if ($target.is('#btnUpdate')) {
                $(this).find("td:first > input[value=Update]").click(function() {
                    UpdateRow(TRID);
                });
            }
            else if ($target.is('#btnCancel')) {
                 $(this).find("td:first > input[value=Cancel]").click(function() {
                     CancelEdit(TRID);
                });
            }                
            else if ($target.is('#btnDelete')) {
                $(this).find("td:first > input[value=Delete]").click(function() {
                    DeleteRow(TRID);
                });
            }
        });
    });

HTML codes looks like this:

<ItemTemplate>
  <tr id='<%# Eval("ContactID") %>'>
        <td width="10%">                       
            <input type="button" value="Edit" id="btnEdit"/>
            <input type="button" value="Delete" id="btnDelete"/>
            <input type="button" value="Update" style="display:none" id="btnUpdate" />
            <input type="button" value="Cancel" style="display:none" id="btnCancel"/>
        </td>
        <td width="10%" align="center"><%# Eval("ContactID")%></td>
        <td width="20%" align="center"><%# Eval("Title")%></td>
        <td width="20%" align="center"><%# Eval("MiddleName")%></td>
        <td width="20%" align="center"><%# Eval("LastName")%></td>
        <td width="20%" align="center"><%# Eval("EmailAddress")%></td>
   </tr>   
</ItemTemplate>

2条回答
女痞
2楼-- · 2019-09-03 14:42

You could take advantage of DOM traversal and .live() to make this work. Add a listener using .live() to the rows of the table. Inside this method, determine which element was clicked (e.currentTarget). You can use a simple conditional to check if it was a button that needs to react. Then, use DOM traversal to nail down what you want to have happen. For example, if e.currentTarget is the delete button, the you can use $(this).closest('tr').remove(); to delete the row. If you need to interact with the data through ajax, make your ajax function support passing in whatever valus you'd need (id) to perform the delete. In order to obtain the id, you'll need to get it from the ajax call and put it somewhere inside the DOM so you can retrieve it when you need it. You can always toss in a 'title' attribute when the tr is generated.

查看更多
倾城 Initia
3楼-- · 2019-09-03 14:48

Here is a same script with php http://www.amitpatil.me/add-edit-delete-rows-dynamically-using-jquery-php/

    // Add new record
$(document).on("click","."+editbutton,function(){
    var id = $(this).attr("id");
    if(id && editing == 0 && tdediting == 0){
        // hide editing row, for the time being
        $("."+table+" tr:last-child").fadeOut("fast");

        var html;
        html += "<td>"+$("."+table+" tr[id="+id+"] td:first-child").html()+"</td>";
        for(i=0;i<columns.length;i++){
            // fetch value inside the TD and place as VALUE in input field
            var val = $(document).find("."+table+" tr[id="+id+"] td[class='"+columns[i]+"']").html();
            input = createInput(i,val);
            html +='<td>'+input+'</td>';
        }
        html += '<td><a href="javascript:;" id="'+id+'" class="'+updatebutton+'"><img src="'+updateImage+'"></a> <a href="javascript:;" id="'+id+'" class="'+cancelbutton+'"><img src="'+cancelImage+'"></a></td>';

        // Before replacing the TR contents, make a copy so when user clicks on 
        trcopy = $("."+table+" tr[id="+id+"]").html();
        $("."+table+" tr[id="+id+"]").html(html);   

        // set editing flag
        editing = 1;
    }
});
查看更多
登录 后发表回答