Magento – Javascript in ajax loaded modal popup

ajaxcalendarmagento2template

I'm working on a module that needs to open modal window and show some content inside of it + some js logic.

So I load template with ajax request which works just fine: (simplified template):

<input type="checkbox" id="show_date" name="show_date" class="control-checkbox admin__control-text"/>    
<input name="date" id="date" title="<?php echo __('Date') ?>" value=""
           class="date input-text admin__control-text" type="text"/>



require([
    "jquery",
    "mage/calendar"
], function ($) {
    $('#show_date').on('change', function () {
        console.log('Changed');
    });

    $("#date").calendar({
        buttonText: 'Select date',
        showTime: false,
        beforeShowDay: $.datepicker.noWeekends
    });
});

Afterwards modal window is opened with the template content:

        var modal = $('<div/>').html(content);
        modal.modal({
            title: $.mage.__('Modal'),
            innerScroll: true,
            modalClass: '_image-box',
            buttons: [{
                text: $.mage.__('Save'),
                attr: {
                    'data-action': 'save'
                },
                'class': 'action-primary',
                click: function () {
                }
            }]
        }).trigger('openModal');

When this happens for the first time everything works as expected. The checkbox does its thing and the calendar works as well.

The problem is that when the modal window is opened for second time without page reload(load tempalte with ajax -> open the modal), it breaks. None of the javascript works.

When the js is changed to use .live instead of .on, the checkbox works every time.

I also tried to move calendar initialization out of the template. In this case the calendar is initialized, however after clicking on specific date it does not change value of the text input.

Any ideas how to fix this issue?

Any help would be greatly appreciated.

Best Answer

Main problem with Modal, that Magento remove DOM elements after modal was closed and store template for next call somewhere. After that call was make it's completely new DOM and jQuery recognize is as new too, because of it not previuosly made bindings works.

You can use modal option "opened":

modal.modal({ 
    ...
    opened: function () {
        $('#show_date').on('change', function () {
            console.log('Changed');
        });

        $("#date").calendar({
            buttonText: 'Select date',
            showTime: false,
            beforeShowDay: $.datepicker.noWeekends
        });
    },
    ...
});
Related Topic