简体   繁体   中英

Fire the datepicker onselect event manually

Can anyone tell me how do you trigger the onselect event of datepicker? My code is working well (pulling some data from a database based on the value of datepickers altfield) but when the page loads it doesn't trigger the onselect event on the current date and it doesn't display anything; so I would like to do that manually.

<script>
     $( "#datepicker" ).datepicker
    (
    {
          altField: '#sheet',
          onSelect: function load() {
            $(document).ready(function() {
                    $.ajax({
                    type: 'POST',
                    url: 'test.php',
                    data: {sheetid: $('#sheet').val()},
                    success: function(data)
                    {
                        $("#content").html(data);
                    }
                });

        });
        },
          firstDay: 1});
    </script>

You can trigger a click on the datepicker right after the set of the date.

Code:

$(document).ready(function () {
    $("#datepicker").datepicker({
        altField: '#sheet',
        onSelect: function(date) {
            alert(date);
        },
        firstDay: 1
    });

    $('#datepicker').datepicker("setDate", new Date(2013,09,22) );
    $('.ui-datepicker-current-day').click(); // rapresent the current selected day

});

Demo: http://jsfiddle.net/IrvinDominin/DynuW/

I took this from the source code of the datepicker.js file. Note that this should be replaced with your input element (not the jquery object, the actual dom element). In my case, I was calling this from a keydown event.

// this is SUCH a hack.  We need to call onselect to call any
// specific validation on this input.  I stole this from the datepicker source code.
var inst = $.datepicker._getInst(this),
onSelect = $.datepicker._get(inst, "onSelect");
if (onSelect) {
    dateStr = $.datepicker._formatDate(inst);
    onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
}

Best solution

var inst = $.datepicker._getInst($("#date")[0]);
$.datepicker._get(inst, 'onSelect').apply(inst.input[0], [$("#date").datepicker('getDate'), inst]);

This is the only solution I found that also works for a datetimepicker

 var $calendar =$('#from'); $.datepicker._getInst($calendar[0]).settings.onSelect()//or onClose or any event 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM