Search code examples
javascriptjquerydatatablesadminlte

jquery.dataTables with hidden columns crash my JQuery


I am using the datatables library in an AdminLTE. I use a small JQuery code to bring the data to an edit modal.

$(document).ready(function () {
/* =========================================================
      EDITAR ALERGENOS
==========================================================*/
$(".btn-warning").click(function (e) {
    e.preventDefault();
    $('#alergenoEditModal').modal('show');
    // capturamos la informacion de la fila
    var alergeno = e.currentTarget.parentElement.parentNode;
    var nombre_ES = alergeno.children[1].innerHTML;
    var nombre_CA = alergeno.children[2].innerHTML;
    var nombre_EN = alergeno.children[3].innerHTML;
    var nombre_DE = alergeno.children[4].innerHTML;

    $('#edit_nombre_ES').val(nombre_ES);
    $('#edit_nombre_CA').val(nombre_CA);
    $('#edit_nombre_EN').val(nombre_EN);
    $('#edit_nombre_DE').val(nombre_DE);

});

});

Everything works until the moment when the columns are hidden to be responsive. At that moment the action does not respond to me.

In full screen we press the yellow edit button. enter image description here

And the modal appears with the data to edit. All right.

enter image description here

However, when the screen is reduced and the buttons are hidden ... enter image description here

We press the blue button to bring up the yellow edit button ... ... and it doesn't work

enter image description here

I don't understand where the problem is.


Solution

  • You have to use event delegation for dynamically added elements. Try this -

    $(document).ready(function () {
    
        $(document).on('click', ".btn-warning", function (e) {
            e.preventDefault();
            $('#alergenoEditModal').modal('show');
            // capturamos la informacion de la fila
            var alergeno = e.currentTarget.parentElement.parentNode;
            var nombre_ES = alergeno.children[1].innerHTML;
            var nombre_CA = alergeno.children[2].innerHTML;
            var nombre_EN = alergeno.children[3].innerHTML;
            var nombre_DE = alergeno.children[4].innerHTML;
    
            $('#edit_nombre_ES').val(nombre_ES);
            $('#edit_nombre_CA').val(nombre_CA);
            $('#edit_nombre_EN').val(nombre_EN);
            $('#edit_nombre_DE').val(nombre_DE);
    
        });
    
    });