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

时间:2011-12-06 20:32:22

标签: javascript jquery datepicker

只有在输入字段的文本不符合一组条件时才需要启动.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;
    }
}

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

感谢。

2 个答案:

答案 0 :(得分:3)

如果你在jQuery UI中使用datepicker,你会像这样显示datepicker:

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

答案 1 :(得分:0)

好的,经过许多百事可乐Max的研究,甚至更多的研究,试验和错误;这就是我想出来的......它满足了我的需求。

$(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次!?我现在没有时间找出一种方法将所有这些都推到一个函数中,这个函数将在循环中启动所有这些...

对此有任何建议将不胜感激。