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

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

当然在HTML中…

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

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


当前回答

为了在加载时将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 
        });
  });

其他回答

var myDate = new Date();
var prettyDate =(myDate.getMonth()+1) + '/' + myDate.getDate() + '/' +
        myDate.getFullYear();
$("#date_pretty").val(prettyDate);

似乎很管用,但也许还有更好的办法。

David K Egghead的代码工作得很完美,谢谢!

$(".date-pick").datepicker(); 
$(".date-pick").datepicker("setDate", new Date()); 

我也设法修剪了一下,它也有用:

$(".date-pick").datepicker().datepicker("setDate", new Date()); 

这对我来说更好,因为有时我有麻烦调用.datepicker('setDate', new Date());因为它混乱,如果我有datepicker已经配置了参数。

$("#myDateText").val(moment(new Date()).format('DD/MM/YYYY'));

更新:有报道称,这将不再适用于Chrome浏览器。

这句话简明扼要,能起到作用(过时):

$(".date-pick").datepicker('setDate', new Date());

这是不那么简洁的,利用链接允许它在chrome中工作(2019-06-04):

$(".date-pick").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属性并不会更新相关的控件。