load plugin datepicker into page call with ajax

2

I'm using the datepicker plugin

All my datepicker input, has the class named datepicker

<input type="text" class="datepicker">

So, I have only one setting for the datepicker and I can use it on all pages, so I set it to a dateconfig.js file, in that file I only have the following code:

 $(".datepicker").datepicker({
        dateFormat: 'dd/mm/yy',
        dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado','Domingo'],
        dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
        dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
        monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
        monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez']
    });

But I have a page with a table and there is input with class="datepicker"

But when I call a modal via ajax, and there is also a input , it does not load the plugin, so on the modal page I copy the configuration code and add it inside a <script> // tag I'm not sure how to do this, but I'm not sure how to do this, but I'm not sure how to do it.

How could I solve these two problems?

Edit

The way I currently call the modal is this:

in my "index / grid / table"

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" id="modalContent">
        </div>
    </div>
</div>

My call of </script> , I used a table of plugin , but I believe it is interpreted as this call of datepicker :

        $.ajax({
            type: "GET",
            url: "URL",
            success: function (result) {
                $("#modalContent").html(result);
            },
            complete: function (msg) {
                $('#myModal').modal('show');
            }
        });
    
asked by anonymous 01.04.2015 / 02:53

4 answers

1

I would change the file dateconfig.js so it can deal with datepicker in a more pragmatic way:

Solution

// Opções para o Datepicker
var options = {
    dateFormat: 'dd/mm/yy',
    dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado','Domingo'],
    dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
    dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
    monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
    monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez']
};

// Controlo para instanciar e/ou apresentar o datepicker
$("body").on("click", ".datepicker", function(){

    var $this = $(this);

    if (!$this.hasClass("hasDatepicker")) {
        $this.datepicker(options);
    }

    $this.datepicker("show");
});

Explanation

  • We are delegating an event to the body element that will fire every time you click an element with class datepicker .

  • The datepicker plugin when creating an instance leaves the control class hasDatepicker in the elements. This allows us to check if the element that received the click already has an instance and thus move on to the calendar presentation.

  • Finally, when clicking on the elements with class datepicker we will open the same.

  • In this way, either asynchronously or in a "regular" way, all the work related to the datepicker is done in your dateconfig.js file and you do not need to take additional steps to manage the < in> plugin .

    Example

    The example below is also in JSFiddle .

    // Opções para o Datepicker
    var options = {
        dateFormat: 'dd/mm/yy',
        dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado','Domingo'],
        dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
        dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
        monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
        monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez']
    };
    
    // Controlo para instanciar e/ou apresentar o datepicker
    $("body").on("click", ".datepicker", function(){
        
        var $this = $(this);
        
        if (!$this.hasClass("hasDatepicker")) {
            $this.datepicker(options);
        }
        
        $this.datepicker("show");
    });
    
    
    // Gerar elementos simulando chamada Ajax
    $('button').on("click", function(){ $('body').append($('<input/>').addClass('datepicker'))});
    <link href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script><scriptsrc="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    
    <input type="text" class="datepicker"> <button>+</button>
        
    01.04.2015 / 19:03
    0

    You will have to apply the plugin only on elements that have been loaded via AJAX into the modal container:

    $("#conteiner-do-modal .datepicker").datepicker({
            dateFormat: 'dd/mm/yy',
            dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado','Domingo'],
            dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
            dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
            monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
            monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez']
        });
    

    I'm assuming the modal container has id="conteiner-do-modal" .

    Avoiding repetitions

    In order to have no error repeating, you can create a method that applies the plugin using a jQuery selector, this function will be available globally for anyone who wants to call:

    function setupDatepicker(seletor) {
        $(seletor).datepicker({
            dateFormat: 'dd/mm/yy',
            dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado','Domingo'],
            dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
            dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
            monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
            monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez']
        });
    }
    

    Then in every place you have to call, do as appropriate:

    • on the home page:

      setupDatepicker(".datepicker");
      
    • after loading the modal:

      setupDatepicker("#conteiner-do-modal .datepicker");
      

    The code above in the form of a plugin:

    (function ( $ ) {
    
        $.fn.setupDatepicker = function() {
            this.datepicker({
                dateFormat: 'dd/mm/yy',
                dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado','Domingo'],
                dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
                dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
                monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
                monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez']
            });
            return this;
        };
    
    }( jQuery ));
    

    To use do so:

    • on the home page:

      $(".datepicker").setupDatepicker();
      
    • after loading the modal:

      $("#conteiner-do-modal .datepicker").setupDatepicker();
      
    01.04.2015 / 03:00
    0

    The problem here is that there is content to be dynamically created and it would be necessary to delegate the datepicker to not run duplicate code and thus generate multiple datepicker windows for each input.

    One solution is to create a new instance every time new content is added to the DOM. The best thing is to do this in AJAX champaign like this:

    var formato = {
        dateFormat: 'dd/mm/yy',
        dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado','Domingo'],
        dayNamesMin: ['D','S','T','Q','Q','S','S','D'],
        dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sáb','Dom'],
        monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
        monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez']
    };
    
    // ... depois dentro do ajax: 
    
    complete: function (msg) {
        $('#myModal').modal('show');
        $("#conteiner-do-modal .datepicker").datepicker(formato);
    }
    

    and thus only the new inputs will be selected.

    Another solution is to call the datepicker by delegating an event, eg focusin:

    $("body").on("input.datepicker", "focusin", function(){
       $(this).datepicker(formato);
    });
    

    Example: link

        
    01.04.2015 / 16:18
    0

    To begin, you can set the settings using the setDefaults function.

    $.datepicker.setDefaults({
        dateFormat: 'dd/mm/yy'
    });
    

    Now, to add the datepicker only to inputs with class datepicker and do not yet have the datepicker initialized, you can do the following:

    $(".datepicker:data(datepicker)").datepicker();
    

    How does it work? The plugins of jquery ui always store in the element the instance of the created object, using the name of the plugin (in this case, datepicker ). So, to check if the plugin has already been initialized in the element, just check for the existence of the instance in it.

    A final version of your code could be as follows:

    function iniciarDatepicker() {
        // você pode passar as configurações aqui ou setar via o setDefults
        $(".datepicker:data(datepicker)").datepicker();
    }
    

    So you can always call the same function.

        
    01.04.2015 / 17:02