JQuery Datepicker, can't trigger onSelect event manually!
Asked Answered
C

9

9

I am using jquery's datepicker where a list of items is populated from an ajax call whenever a date is picked from an inline datepicker object. The script works perfect except that I can't trigger an onSelect event to populate my initial list of items.

I could get around this problem by just populating the list initially using php but I would really like to avoid this.

    $(document).ready(function(){

        //create date pickers
    $("#date_calendar").datepicker(
  { 
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm-dd',
        defaultDate: $.datepicker.parseDate("y-m-d", $('#date').val()),
        onSelect: function(dateText, inst)
            {
                alert('onSelect triggered! Yay!');
                $('#date').val($.datepicker.formatDate("yy-mm-dd", $('#date_calendar').datepicker('getDate')));

                // Ajax for populating days when selected
                $.post(
                    "server_requests/show_day.php",
                        {
                        date: $('#date').val(),
                        user_id: $('#user_id').val()
                        },
                    function(data)
                    {
                        //return function
                        $('#my_day_tasks').html(data.resultTable);
                    },
                    "json"
                );
            }
    }).disableSelection();

    $("#date_calendar").trigger('onSelect');

});

Any help is appreciated :)

Cadmium answered 28/1, 2010 at 15:12 Comment(0)
C
13

Couldn't you just refactor that to a function of its own, which you reuse? Strictly speaking, a datepicker select is not really what happens on page load. You just want to do exactly the same thing that happens when the datepicker is indeed selected.

function populateList(dateText, inst)
{
    alert('alert test');
    $('#date').val($.datepicker.formatDate("yy-mm-dd",$('#date_calendar').datepicker('getDate')));

    // Ajax for populating days when selected
    $.post("server_requests/show_day.php",
        {
            date: $('#date').val(),
            user_id: $('#user_id').val()
        },
        function(data)
        {
            //return function
            $('#my_day_tasks').html(data.resultTable);
        },
        "json"
    );
}

$(document).ready(function(){
  //create date pickers
  $("#date_calendar").datepicker(
  { 
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm-dd',
        defaultDate: $.datepicker.parseDate("y-m-d", $('#date').val()),
        onSelect: populateList
  }).disableSelection();

  // i'm not bothering to pass the input params here, because you're not using them anyway
  populateList(); 

});
Crowell answered 28/1, 2010 at 15:19 Comment(4)
You know... sometimes you look at something so hard you become dumb :) This makes way too much sense. Thanks a million!Cadmium
this only works if youve only got a single datepickerCracow
I already had a separate function like you mention here, but somehow didn't even think to call that manually. Wow. Thank you for your obvious, yet extremely helpful observation!Volution
@ogc-nick just send along the datepicker's id when invoking the function, and use that inside the functionSotos
I
31
$('.ui-datepicker-current-day').click();
Incertitude answered 3/12, 2012 at 23:40 Comment(1)
This was the method I was using at first, but it is not reliable when calling the "setDate" method with a date that takes me to a different month. In that case, using David's solution worked, and it was the most reliable overall.Volution
C
13

Couldn't you just refactor that to a function of its own, which you reuse? Strictly speaking, a datepicker select is not really what happens on page load. You just want to do exactly the same thing that happens when the datepicker is indeed selected.

function populateList(dateText, inst)
{
    alert('alert test');
    $('#date').val($.datepicker.formatDate("yy-mm-dd",$('#date_calendar').datepicker('getDate')));

    // Ajax for populating days when selected
    $.post("server_requests/show_day.php",
        {
            date: $('#date').val(),
            user_id: $('#user_id').val()
        },
        function(data)
        {
            //return function
            $('#my_day_tasks').html(data.resultTable);
        },
        "json"
    );
}

$(document).ready(function(){
  //create date pickers
  $("#date_calendar").datepicker(
  { 
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm-dd',
        defaultDate: $.datepicker.parseDate("y-m-d", $('#date').val()),
        onSelect: populateList
  }).disableSelection();

  // i'm not bothering to pass the input params here, because you're not using them anyway
  populateList(); 

});
Crowell answered 28/1, 2010 at 15:19 Comment(4)
You know... sometimes you look at something so hard you become dumb :) This makes way too much sense. Thanks a million!Cadmium
this only works if youve only got a single datepickerCracow
I already had a separate function like you mention here, but somehow didn't even think to call that manually. Wow. Thank you for your obvious, yet extremely helpful observation!Volution
@ogc-nick just send along the datepicker's id when invoking the function, and use that inside the functionSotos
I
4

Here is what I came up with and seems to be the best solution:

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

And it works like a charm

In answered 26/5, 2015 at 7:57 Comment(2)
This should be an answer.Swaney
This is actually incorrect, $("#date").datepicker('getDate') gives you the Date object, but the first parameter is supposed to be the date string.Bixby
W
3

You could try something like this -

    $(document).ready(function(){
    //when page loads                      
    SetDateTime(null);
    //create date pickers
    $("#date_calendar").datepicker(
  { 
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm-dd',
        defaultDate: $.datepicker.parseDate("y-m-d", $('#date').val()),
        onSelect: function(dateText, inst)
            {
                SetDateTime(dateText);
            }
    }).disableSelection();

    $("#date_calendar").trigger('onSelect');
});

function SetDateTime(selectedDate)
{
    if(selectedDate == null)
    {
        //get todays date
        var dateNow = new Date();
        //if its a single digit day, add a zero before it
        var sDay = dateNow.getDate().toString();
        if(sDay.length == 1)
        {
            sDay = "0" + sDay;
        }
        selectedDate = dateNow.getFullYear() + "-" + (dateNow.getMonth() + 1) + "-" + sDay;

        //load timetable
        ShowDay(selectedDate);
    }
    else
    {
        var ds = selectedDate.split("-");

        //load timetable
        ShowDay(selectedDate);  
    }
}

function ShowDay(dateToday)
{
         alert('onSelect triggered! Yay!');
         $('#date').val($.datepicker.formatDate("yy-mm-dd", $('#date_calendar').datepicker('getDate')));

        // Ajax for populating days when selected
        $.post(
            "server_requests/show_day.php",
                {
                date: dateToday,
                user_id: $('#user_id').val()
                },
            function(data)
            {
                //return function
                $('#my_day_tasks').html(data.resultTable);
            },
            "json"
        );
}
Wallaroo answered 28/1, 2010 at 15:30 Comment(1)
4 space indent, or press the '101010' button, for code format.Crowell
M
3

This is how I got round the same problem. Simply register an event with the code you want to call, then call that event from the onSelect method inside datepicker and then call that same event any other time you want.

$(document).ready(function(){

    // Onselect event registration
    $("#date_calendar").bind("datepickeronSelect", function(){

        alert("onSelect called!");

    })

    //create date pickers
    $("#date_calendar").datepicker(
    { 
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm-dd',
        defaultDate: $.datepicker.parseDate("y-m-d", $('#date').val()),
        onSelect: function(dateText, inst)
        {
            $("#date_calendar").trigger("datepickeronSelect");
        }
    }).disableSelection().trigger("datepickeronSelect");
});
Mothball answered 24/2, 2012 at 0:56 Comment(0)
P
3

there is another solution for find out when a date select.

 $(".uc_datepicker :text").datepicker();
 $(".uc_datepicker :text").click(function() {
    $(".ui-datepicker-calendar a").click(function() {
        alert("date selected");
    });
 });
Parameter answered 17/11, 2012 at 8:43 Comment(0)
T
1

I was trying to do almost the same thing, but in my case I have to shoe appointments on load and not on selection.

Although this is not necessary for your solution, I'd like to add my solution because it might help others who want to do the same on load.

I modified the jquery.ui.datepicker.mobile.js to highlight days with appointments with beforeShowDay, load appointment onSelect etc. You can simply initialize your appointments by adding the following lines at the bottom of the datepicker rewriting function:

//rewrite datepicker
$.fn.datepicker = function( options ){

    // ... all the options and event stuff

    function initAppointments() {
        // select the 'selected' days to trigger the onSelect event#
        // and initalize the appointments within the event handler
        $( ".ui-datepicker-calendar a.ui-state-active", dp ).trigger('click');
        updateDatepicker();
    }

    //update now
    updateDatepicker();

    // and on click
    $( dp ).click( updateDatepicker );
    $( dp ).ready( initAppointments ); // new

    //return jqm obj 
    return this;
};
Talley answered 8/9, 2011 at 13:0 Comment(0)
X
1

The accepted answer was not something I could use, because I was using common code that added hotkey functionality on all datepickers in my web application (to set value to today, +1 day, +1 month, etc.), and wanted to make sure onselect was called to validate the date value that was calculated with the hot key.

I took this from the source code of the datepicker.js file. Note thiat this should be replaced with your datepicker 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]);
}
Xenos answered 14/2, 2014 at 18:0 Comment(1)
Think you deserve the +1 over AdrianPop as your answer was well over a year before his, and yours is more robust. Yours also has the mention of the formatdate, which is necessary for the first parameter of the onSelect function. However, you really should have defined what "this" is referencing. You should let us know that it is the DOM element for the input boxBixby
B
0

I use another way, trigger 2 events

  1. setDate jQuery('#my-calendar').datepicker( "setDate", "09/29/2020" )
  2. Trigger click event jQuery('#my-calendar .ui-state-active').trigger('click')
Bacteriolysis answered 28/9, 2020 at 8:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.