0

I had a table within my MVC 5 View which repeated out rows of data. Each row had a button attached to it which when clicked upon would pass the data-id into a hidden text box using JQuery

MVC View

@foreach (var item Model.MyList) {

//<tr> etc
<td>
  <button class="btn btn-danger btn-xs" id="btnDelete" data-toggle="modal" data-target="#myModal" data-id="@item.ID"> Delete </button>
</td>

}

JQuery

$(document).ready(function () {

    //Everytime we press delete in the table row
    $('.btn.btn-danger').click(function () {

        //Update the text box with delete id so our model knows which one to delete

        $('#item-to-delete').val(id);

    });

});

I then decided to replace my table with https://datatables.net/ for several reasons. The problem now, is that when the user clicks the Delete button inside the Datatable, my JQuery click function is no longer called and therefore the delete ID is not passed into my hidden textbox.

This is my DataTable script

<script>
    $(document).ready(function () {
        $('#dataTables-example').dataTable({  
            "bServerSide": true,  
            "sAjaxSource": "/MyController/GetAjaxData",
            "bProcessing": true,
            "bJQueryUI": true,
            "aoColumns": [
                      { "sName": "ID", "visible": false },
                      null, //FullName
                      null, //Email
                      null, //LastLoginDate
                      {
                          "mData": null,
                          "mRender": function (data, type, full) {
                              return "<button class='btn btn-danger btn-xs' id='btnDelete' data-toggle='modal' data-target='#myModal' data-id='"+ full[0] +"'>Delete</button>";

                          }
                      }

            ]
        });  
    });  
</script>

Can anyone please see why this is happening or advise me on how to fix the problem?

Thanks alot.

tcode
  • 5,055
  • 19
  • 65
  • 124

1 Answers1

1

Instead of $('.btn.btn-danger').click(function ()...

Try use .on to bind the event to a later created dom element.

Many people have already asked this question. See jQuery function not binding to newly added dom elements

Community
  • 1
  • 1
Blaise
  • 21,314
  • 28
  • 108
  • 169