我有一个非常简单的jQuery Datepicker日历:

$(document).ready(function(){
    $("#date_pretty").datepicker({ 
    });
});

当然在HTML中…

<input type="text" size="10" value="" id="date_pretty"/>

今天的日期是很好的突出显示为用户时,他们带来的日历,但我如何让jQuery预填充文本框本身与今天的日期在页面加载,而不需要用户做任何事情?99%的情况下,今天的日期默认是他们想要的。


当前回答

今天开始:

$('#date_pretty').datepicker('setDate', '+0');

设置为昨天:

$('#date_pretty').datepicker('setDate', '-1');

在今天日期之前或之后的任何天数都可以如此。

查看jQuery UI›方法›setDate。

其他回答

为了在加载时将datepicker设置为某个默认时间(在我的情况下是当前日期),然后有选项选择另一个日期,语法是:

    $(function() { 
        // initialize the datapicker
        $("#date").datepicker();

        // set the time
        var currentDate = new Date();
        $("#date").datepicker("setDate",currentDate);

    //  set the options for the button  
        $("#date").datepicker("option",{
            dateFormat: 'dd/mm',
            showOn: "button",
          // whatever option Or event you want 
        });
  });

这段代码将确保使用你的datepicker的格式:

$('#date-selector').datepicker('setDate', new Date());

不需要重新应用格式,它使用预定义的datepicker -由你在datepicker初始化(如果你已经分配了它!);)

你有两个选择:

选项A)在日历中标记为“活动”,仅当您单击输入时。

Js:

$('input.datepicker').datepicker(
                        {   
                            changeMonth: false,
                            changeYear: false,
                            beforeShow: function(input, instance) { 
                                $(input).datepicker('setDate', new Date());
                            }
                        }                         
                     );

Css:

div.ui-datepicker table.ui-datepicker-calendar .ui-state-active,
        div.ui-datepicker table.ui-datepicker-calendar .ui-widget-content .ui-state-active  {
            background: #1ABC9C;
            border-radius: 50%;
            color: #fff;
            cursor: pointer;
            display: inline-block;
            width: 24px; height: 24px;
        }​

选项B)默认输入今天。 您必须首先填充datepicker。

$("input.datepicker").datepicker().datepicker("setDate", new Date());

setDate()方法的作用是:设置日期并更新相关控件。以下是如何做到的:

$("#datepicker1").datepicker({
    dateFormat: "yy-mm-dd"
}).datepicker("setDate", "0");

Demo

正如在文档中提到的,setDate()愉快地接受JavaScript Date对象,数字或字符串:

新的日期可以是date对象,也可以是当前日期中的字符串 格式(如。'01/26/2009')、从今天算起的天数(例如+7)或a 值和周期字符串('y'表示年,'m'表示月,'w'表示 Weeks,“d”表示天。'+1m +7d'),或null以清除所选对象 日期。

如果您想知道,在构造函数中设置defaultDate属性并不会更新相关的控件。

用这个:

$ (" .datepicker”)。datepicker({dateFormat: 'dd-M-yy'})。datepicker('setDate', new Date());

以格式获取日期,例如:10-Oct-2019,这对用户来说更容易理解。