Search code examples
javascriptjquerydatatableconfirm

jQuery off seems not working for images inside a dataTable


I have a dataTable and in each row there is an clickable icon that popups a confirm message, if the confirm button is clicked, the next time the icon were clicked no message must appear. As the rows are filled programatically, each icon has the same id name and class. The code is shown below

$('#myTable tbody').on( 'click', 'img.sc', function () {
    $.confirm({
    title: 'Confirm!',
    content: 'You will report an issue..',
    buttons: {
    confirm: function () {
             $(this).off('click' );
             //other stuff ..}
    cancel: function () {
             $.alert('Canceled!');
                      },
             }
     });
});

This code doesn't work, the icon shows the message each time it is clicked. I tried also with the one() method but after clicked an icon, this made unresponsive all the icons in the table. How can I fix this?


Solution

  • Not sure if $(this) refers to the element here. Try the following:

        $('#myTable tbody').on('click', 'img.sc', function() {
            let elem = $(this);
            $.confirm({
                title: 'Confirm!',
                content: 'You will report an issue..',
                buttons: {
                    confirm: function() {
                        elem.off('click');
                        //other stuff ..
                    },
                    cancel: function() {
                        $.alert('Canceled!');
                    },
                }
            });
        });