Search code examples
javascriptjqueryajaxtwitter-bootstrapdatepicker

jQuery datepickers not initializing each time modal is loaded


I am using modals in my web application for user input. The first time a user uses a modal to input data it works with no issue. However, if the user opens another modal after the first, the jQuery datepickers do not initialize. The user must refresh the page in order to be able to user the datepicker to input a second record. The modal body is loaded via AJAX. At the bottom of the HTML file which contains the modal body, some a script is incldued to init the datepickers. Here is the general structure of the modal content:

<div class="modal-content">
    <div class="modal-header">
    ...more modal content goes here...
    </div>
</div>

<script>
    $('.date-picker').datepicker({
        rtl: App.isRTL(),
        autoclose: true
    });
</script>

It is not an option to simply include this on the requesting page since some content is generated by PHP (ie. when editing a record). How can I resolve this issue?


Solution

  • The issue was that the script was only being fired the first time that the modal is shown. I resolved it by overriding the default remote modal load function in ajax with the following:

    $("[data-toggle='open_modal']").click(function(event) {
            event.preventDefault();
            $modal = $($(this).attr("data-target"));
            $modal.modal().find('.modal-content').load($(this).attr('href'), function() {
                $('.date-picker').datepicker({
                    rtl: App.isRTL(),
                    autoclose: true
                });
            });
        });
    

    Note that you cannot leave data-toggle='modal' since it will try to use the bootstrap loading function at the same time. Change it to something else, ie. open_modal.