从另一个JS函数中启动jQuery .datepicker

Launch jQuery .datepicker from Another JS Function

本文关键字:启动 jQuery datepicker 函数 另一个 JS      更新时间:2023-09-26

只有当输入到字段中的文本不符合一组标准时,我才需要启动。datepicker。但是,我不知道如何启动。datepicker,而不是直接从一个字段获得焦点或一个按钮被按下。

我想做的是…

HTML

<input type="text" id="userDate" name="userDate" style="width: 100px;" onblur="checkDate(this.id);" />

JS

function checkDate(theId)
{
    var enteredValue = document.getElementById(theId).value;
    var checkedValue = evaluateValue(enteredValue); // this checks to see if the text meets the criteria
    if (checkedValue == null)
    {
        // this is where I want to call the .datepicker to have the calendar show up
        $("#userDate").datepicker();
    }
    else
    {
        document.getElementById(theId).value = checkedValue;
    }
}

我知道,如果日历在文本字段得到焦点时出现,这将更容易。但是,这不是客户想要的工作方式。他们想要接受用户输入,只要它符合他们想要的格式。如果没有,那么他们需要日历和默认的强制格式。

谢谢。

如果您在jQuery UI中使用日期拾取器,您将像这样显示日期拾取器:

$("#userDate").datepicker("show");
编辑:

你的代码可能看起来像这样:

$(function(){
   $("#userDate").datepicker(); // <-- Create the datepicker on load
});
function checkDate(theId)
{
    var enteredValue = document.getElementById(theId).value;
    var checkedValue = evaluateValue(enteredValue); // this checks to see if the text meets the criteria
    if (checkedValue == null)
    {
        // this is where I want to call the .datepicker to have the calendar show up
        $("#userDate").datepicker("show");  // <-- Show datepicker when needed
    }
    else
    {
        document.getElementById(theId).value = checkedValue;
    }
}

好了,在喝了很多罐百事可乐之后,在进行了更多的研究、试验和错误之后;这是我想出来的…它满足了我的需求。

$(document).ready( function()
    {
        $("#userDate").blur(function()
        {
            var convertResults = convertMyDate('userDate'); // call to my code that checks the date for accepted formats
            if (convertResults == null)
            {
                $("#userDate").datepicker({
                    changeMonth: true,
                    changeYear: true
                });
                $("#userDate").datepicker("show");
            }
            else
            {
                document.getElementById('userDate').value = convertResults.toString('MM/dd/yyyy');
            }
        });
    });

现在唯一的问题是客户端的表单有14个日期字段。所以…在我的代码中再复制13次!?我现在没有时间来想办法把所有这些都放到一个函数中,这个函数会在一个循环中启动所有这些…