Set today's date as default date in jQuery UI

2019-03-08 12:51发布

This question already has an answer here:

I just want today's date to be the default value in the input that is using jQuery UI's datepicker:

<input id="mydate" type="text" />

I tried the below code but it didn't work:

var currentDate = new Date();  
$("#mydate").datepicker("setDate",currentDate);

13条回答
Deceive 欺骗
2楼-- · 2019-03-08 12:59

You need to make the call to setDate separately from the initialization call. So to create the datepicker and set the date in one go:

$("#mydate").datepicker().datepicker("setDate", new Date());

Why it is like this I do not know. If anyone did, that would be interesting information.

查看更多
冷血范
3楼-- · 2019-03-08 13:01

try this:

$("#mydate").datepicker("setDate",'1d');
查看更多
疯言疯语
4楼-- · 2019-03-08 13:03

This one work for me , first you bind datepicker to text-box and in next line set (today as default date) the date to it

$("#date").datepicker();

$("#date").datepicker("setDate", new Date());
查看更多
霸刀☆藐视天下
5楼-- · 2019-03-08 13:04

You have to initialize the datepicker before calling a datepicker method

Here is a

Working JSFiddle.


$("#mydate").datepicker().datepicker("setDate", new Date());
//-initialization--^          ^-- method invokation
<link href="https://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<input type="text" id="mydate" />


P.S: This assumes that you have the correct date set in your computer

查看更多
We Are One
6楼-- · 2019-03-08 13:05

This worked for me and also localised it:

$.datepicker.setDefaults( $.datepicker.regional[ "fr" ] );
$(function() {
   $( "#txtDespatchDate" ).datepicker( );
   $( "#txtDespatchDate" ).datepicker( "option", "dateFormat", "dd/mm/yy" );
   $('#txtDespatchDate').datepicker('setDate', new Date());
});
查看更多
Deceive 欺骗
7楼-- · 2019-03-08 13:06

Try this:

$('.datepicker').datepicker('update', new Date(year,month,day));
查看更多
登录 后发表回答