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 :)

9 Answers 9

32
$('.ui-datepicker-current-day').click();
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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(); 

});

4 Comments

You know... sometimes you look at something so hard you become dumb :) This makes way too much sense. Thanks a million!
this only works if youve only got a single datepicker
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!
@ogc-nick just send along the datepicker's id when invoking the function, and use that inside the function
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

2 Comments

This should be an answer.
This is actually incorrect, $("#date").datepicker('getDate') gives you the Date object, but the first parameter is supposed to be the date string.
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"
        );
}

1 Comment

4 space indent, or press the '101010' button, for code format.
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");
});

Comments

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");
    });
 });

Comments

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;
};

Comments

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]);
}

1 Comment

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 box
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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.