JQuery Datepicker,无法手动触发onSelect事件!

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2155485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:53:42  来源:igfitidea点击:

JQuery Datepicker, can't trigger onSelect event manually!

jqueryevent-handlingdatepicker

提问by Gazillion

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.

我正在使用 jquery 的日期选择器,其中每当从内联日期选择器对象中选择日期时,就会从 ajax 调用中填充项目列表。该脚本完美无缺,只是我无法触发 onSelect 事件来填充我的初始项目列表。

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

我可以通过最初使用 php 填充列表来解决这个问题,但我真的很想避免这种情况。

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

任何帮助表示赞赏:)

回答by flatr0ze

$('.ui-datepicker-current-day').click();

回答by dxh

Couldn't you just refactor that to a function of its own, which you reuse? Strictly speaking, a datepicker select is not reallywhat 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(); 

});

回答by AdrianPop

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

它就像一个魅力

回答by TGuimond

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

回答by Simon

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.

这就是我如何解决同样的问题。只需使用您要调用的代码注册一个事件,然后从 datepicker 内的 onSelect 方法调用该事件,然后在您想要的任何其他时间调用相同的事件。

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

回答by mehdi

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

回答by Smamatti

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.jsto highlight days with appointments with beforeShowDay, load appointment onSelectetc. You can simply initialize your appointments by adding the following lines at the bottom of the datepicker rewriting function:

我修改了jquery.ui.datepicker.mobile.js以突出显示与beforeShowDay约会的日期,加载约会onSelect等。您可以通过在 datepicker 重写功能底部添加以下行来简单地初始化您的约会:

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

回答by scott.korin

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.

接受的答案不是我可以使用的,因为我使用的是通用代码,这些代码在我的 Web 应用程序中的所有日期选择器上添加了热键功能(将值设置为今天、+1 天、+1 个月等),并且想要使确定调用 onselect 来验证使用热键计算的日期值。

I took this from the source code of the datepicker.js file. Note thiat thisshould be replaced with your datepicker element. In my case, I was calling this from a keydownevent.

我从 datepicker.js 文件的源代码中获取了这个。请注意 thiatthis应替换为您的日期选择器元素。就我而言,我是从一个keydown事件中调用它的。

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