8

i have a problem with this project.

I'm trying to create a crud menu, when hitting the Edit button the row's data will be transferred to a bootstrap modal and from there user will be able to edit.

Problem : right now when hitting the row - the modal opens perfectly with the row's data - but when i try to change it to get the data by pressing on the button ('.edit_btn') ,it dos't works. i know that the button doesn't holds any data - so that's why it's probably don't work....

 $('#example tbody').on('click',  '.edit_btn', function () { // works only 
    when replacing 'tr' with  '.edit_btn' //
    var data_row = table.row(this).data(); // row's data

    $("#myModal").modal('show');

    $('#myModal').on('shown.bs.modal', function() {

        $('#name').val(data_row.id);
        $('#type').val(data_row.type);
        $('#camp').html(data_row.campaign);

    });

});

Thanks

2 Answers 2

18

I would use a delegated event handler tbody .edit_btn and grab the row through closest('tr') :

$('#example').on('click', 'tbody .edit_btn', function () {
    var data_row = table.row($(this).closest('tr')).data();
    ...
})

forked plunkr -> https://plnkr.co/edit/58vkkp3M6d68uuMknXus?p=preview

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

2 Comments

@RoyBarOn The delegation just to be sure it works on all pages (on a paginated table) and closest() to be sure the right <tr> is used for data-retrieval.
davidkonrad - Thanks
4

Got it...

$('#example tbody').on('click', '.edit_btn', function () {

     var data_row = table.row( $(this).parents('tr') ).data(); // here is the change
    $("#myModal").modal('show');

    $('#myModal').on('shown.bs.modal', function() {

       $('#name').val(data_row.id);
        $('#type').val(data_row.type);
        $('#camp').html(data_row.campaign);

    });

});

1 Comment

If you set DataTable to responsive and open in small device, this method will fail, because column will reduced in different parents.

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.