jQuery UI Datepicker : Set Current Date

To set current date in control to which jQuery UI datepicker bind, use setDate() method. Pass date object which needs to be set as an argument to setDate() method. If you want to set it to current date then you can pass 'today' as argument.

So, jQuery code to set current date may look like something similar,

$(document).ready(function() {
    $('#txtDate').datepicker('setDate', 'today');
});?

But Wait!!! Above jQuery code will not work. It will not set the current date. Wondering why?

Well, as I told you that setDate() is a method, not an option. And to call the any object, object must be initialized. And in this case, datepicker is not even initialized. So correct way is,

$(document).ready(function() {
    $('#txtDate').datepicker();
    $('#txtDate').datepicker('setDate', 'today');
});?

OR

$(document).ready(function() {
    $('#txtDate').datepicker().datepicker('setDate', 'today');
});?

See result below


Other method is,

$(document).ready(function() {
    $('#txtDate').datepicker();
    $('#txtDate').datepicker('setDate', new Date());
});?

Note: Please set the date format as per your need, otherwise it will use date format of client machine.

$(document).ready(function() {
    $('#txtDate').datepicker({ dateFormat: 'yy/mm/dd' });
    $('#txtDate').datepicker('setDate', new Date());
});?

As mentioned earlier, the setDate() method takes date object as argument so you can also set any specific date as well. For example, to set 31-Dec-2000 as date

$(document).ready(function() {
    var myDate = new Date(2000,11,31);
    $('#txtDate').datepicker();
    $('#txtDate').datepicker('setDate', myDate);
});?

You can also pass the date as string.

$(document).ready(function() {
    $('#txtDate').datepicker();
    $('#txtDate').datepicker('setDate', '12/31/2000');
});?

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...