3

I have a jQuery function which looks like this:

function unlock_reservation_columns(resid) {

    $('.unlock-columns').click( function(event) {

        event.preventDefault();
        $(this).closest('tr').find('.columns-locked').removeClass('columns-locked');
        $(this).html('<i class="fa fa-lock"></i> Lock Columns');
        $(this).attr('class', 'lock-columns');

        new PNotify({
            title: 'We have unlocked this reservation..',
            text: 'Reservation Unlocked',
            type: 'success'
        });
        var url = $(this).attr("href");
        var url_id = url.replace(/[^0-9]/g, '')
        $.get(url, function (data) {

            var confirm_changes = confirm('Do you wish to edit unlocked information?');

            if (confirm_changes) {
                window.location.href = '/reservations/database/edit/' + url_id;
            }
            else {
                location.reload()
                return false;
            }
        });
    });
});

<a class="unlock-columns" href="<?php echo $row->unlock_url; ?>"><i class="fa fa-unlock"></i> Unlock Columns</a>

The button "unlock-columns" is located inside a Datatable custom column. Now when the page is only initialized this button works fine. After i sort something in the table. the (data-order-by) and click the button it doesn't work.. like after sorting it stops working. any ideas why?

Ilanus
  • 6,690
  • 5
  • 13
  • 37

1 Answers1

5

Use a delegated event handler

$('#tableId').on('click', '.unlock-columns', function(event) {

instead. As it is now you only attach the click handler to visible rows upon initialisation, not rows injected later on (as when you are paginating, sorting etc).

davidkonrad
  • 83,997
  • 17
  • 205
  • 265
  • Awesome! seems to be working now.. could you explain when the delegated event handler needs to be used? and what why it works now – Ilanus Oct 02 '15 at 08:18
  • 3
    @IlanHasanov: See [this](http://stackoverflow.com/questions/8110934/direct-vs-delegated-jquery-on/8111171#8111171) answer. – D4V1D Oct 02 '15 at 08:18