0

I suppose my function isn't correctly defined since when I replace table html code, table rows don't trigger anymore the function they are bound with.

Here is my HTML table:

<tr class="open-row-modal" href="/dashboard_staff/settings/ajax_update_period/1" data-toggle="modal" data-target="#form-modal">
          <td>bla bla</td>
          <td>30,00</td>
</tr>

And my javascript code:

var formAjaxSubmit = function(form, modal, obj_to_replace = false) {
    $(form).submit(function (e) {
        e.preventDefault();
        $.ajax({
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function (xhr, ajaxOptions, thrownError) {
                if ( $(xhr).find('.has-error').length > 0 ) {
                    $(modal).find('.modal-body').html(xhr);
                    formAjaxSubmit(form, modal);
                } else {
                    $(modal).modal('toggle');

                    if (obj_to_replace !== false) {
                        $(modal).modal('toggle');
                        obj_to_replace.parentNode.innerHTML = xhr;
                    }
                }},
            error: function (xhr, ajaxOptions, thrownError) {
                // handle response errors here
            }
        });
    });
};

$('.open-row-modal').click(function() {
    var url = $(this)[0].attributes.href;
    var parent_card = findAncestor($(this)[0], 'card-default');
    let load = $('#form-modal-body').load(url.value, function () {
        $('#form-modal').modal('toggle');
        formAjaxSubmit('#form-modal-body form', '#form-modal', parent_card);
    });
});

function findAncestor (el, cls) {
    while ((el = el.parentElement) && !el.classList.contains(cls));
    return el;
}

When the table is replaced, the click function is not triggered anymore.

Emilio Conte
  • 1,105
  • 10
  • 29

1 Answers1

1

I think it's because the elements are dynamically updated. Try using event delegation to handle the event. In jquery, try using .on() to attach the click event to the document selectors

$(document).on('click','.open-row-modal',function() {

See https://api.jquery.com/on/ for documentation about the .on() event handler.