[javascript] How do I pre-populate a jQuery Datepicker textbox with today's date?

I have a very simple jQuery Datepicker calendar:

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

and of course in the HTML...

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

Today's date is nicely highlighted for the user when they bring up the calendar, but how do I get jQuery to pre-populate the textbox itself with today's date on page load, without the user doing anything? 99% of the time, the today's date default will be what they want.

This question is related to javascript jquery jquery-ui date jquery-ui-datepicker

The answer is


Set to today:

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

Set to yesterday:

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

And so on with any number of days before or after today's date.

See jQuery UI › Methods › setDate.


$(function()
{
$('.date-pick').datePicker().val(new Date().asString()).trigger('change');
});

Source: http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerDefaultToday.html


Set to today:

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

Set to yesterday:

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

And so on with any number of days before or after today's date.

See jQuery UI › Methods › setDate.


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

seemed to work, but there might be a better way out there..


$(function()
{
$('.date-pick').datePicker().val(new Date().asString()).trigger('change');
});

Source: http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerDefaultToday.html


Use This:

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

To Get Date in Format Eg: 10-Oct-2019 which will be more understandable for users.


David K Egghead's code worked perfectly, thank you!

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

I also managed to trim it a little and it also worked:

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

Use This:

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

To Get Date in Format Eg: 10-Oct-2019 which will be more understandable for users.


This one worked for me.

$('#inputName')
  .datepicker()
  .datepicker('setDate', new Date());

You must FIRST call datepicker() > then use 'setDate' to get the current date.

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

OR chain your setDate method call after your datepicker initialization, as noted in a comment on this answer

$('.date-pick').datepicker({ /* optional option parameters... */ })
               .datepicker("setDate", new Date());

It will NOT work with just

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

NOTE : Acceptable setDate parameters are described here


David K Egghead's code worked perfectly, thank you!

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

I also managed to trim it a little and it also worked:

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

This works better for me as sometimes I have troubles calling .datepicker('setDate', new Date()); as it messes if if i have the datepicker already configured with parameters.

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

$('input[name*="date"]').datepicker({
        dateFormat: 'dd-mm-yy',
        changeMonth: true,
        changeYear: true,
        beforeShow: function(input, instance) { 
            $(input).datepicker('setDate', new Date());
        }
    });

To pre-populate date, first you have to initialise datepicker, then pass setDate parameter value.

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

This one worked for me.

$('#inputName')
  .datepicker()
  .datepicker('setDate', new Date());

This code will assure to use your datepicker's format:

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

No need to re-apply format, it uses the datepicker predefined-one by you on datepicker initialization (if you have assigned it!) ;)


The solution is:

$(document).ready(function(){
    $("#date_pretty").datepicker({ 
    });
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var prettyDate = month + '/' + myDate.getDate() + '/' + myDate.getFullYear();
    $("#date_pretty").val(prettyDate);
});

Thanks grayghost!


var prettyDate = $.datepicker.formatDate('dd-M-yy', new Date());
alert(prettyDate);

Assign the prettyDate to the necessary control.


You must FIRST call datepicker() > then use 'setDate' to get the current date.

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

OR chain your setDate method call after your datepicker initialization, as noted in a comment on this answer

$('.date-pick').datepicker({ /* optional option parameters... */ })
               .datepicker("setDate", new Date());

It will NOT work with just

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

NOTE : Acceptable setDate parameters are described here


The solution is:

$(document).ready(function(){
    $("#date_pretty").datepicker({ 
    });
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var prettyDate = month + '/' + myDate.getDate() + '/' + myDate.getFullYear();
    $("#date_pretty").val(prettyDate);
});

Thanks grayghost!


Just thought I'd add my two cents. The picker is being used on an add/update form, so it needed to show the date coming from the database if editing an existing record, or show today's date if not. Below is working fine for me:

    $( "#datepicker" ).datepicker();
    <?php if (!empty($oneEVENT['start_ts'])): ?>
       $( "#datepicker" ).datepicker( "setDate", "<?php echo $startDATE; ?>" );
    <? else: ?>
       $("#datepicker").datepicker('setDate', new Date());   
    <?php endif; ?>
  });

In order to set the datepicker to a certain default time (the current date in my case) on loading, AND then have the option to choose another date the syntax is :

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

This code will assure to use your datepicker's format:

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

No need to re-apply format, it uses the datepicker predefined-one by you on datepicker initialization (if you have assigned it!) ;)


You've got 2 options:

OPTION A) Marks as "active" in your calendar, only when you click in the input.

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;
        }?

OPTION B) Input by default with today. You've to populate first the datepicker .

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

The solution is:

$(document).ready(function(){
    $("#date_pretty").datepicker({ 
    });
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var prettyDate = month + '/' + myDate.getDate() + '/' + myDate.getFullYear();
    $("#date_pretty").val(prettyDate);
});

Thanks grayghost!


The setDate() method sets the date and updates the associated control. Here is how:

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

Demo

As mentioned in documentation, setDate() happily accepts the JavaScript Date object, number or a string:

The new date may be a Date object or a string in the current date format (e.g. '01/26/2009'), a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null to clear the selected date.

In case you are wondering, setting defaultDate property in the constructor does not update the associated control.


The solution is:

$(document).ready(function(){
    $("#date_pretty").datepicker({ 
    });
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var prettyDate = month + '/' + myDate.getDate() + '/' + myDate.getFullYear();
    $("#date_pretty").val(prettyDate);
});

Thanks grayghost!


You've got 2 options:

OPTION A) Marks as "active" in your calendar, only when you click in the input.

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;
        }?

OPTION B) Input by default with today. You've to populate first the datepicker .

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

var prettyDate = $.datepicker.formatDate('dd-M-yy', new Date());
alert(prettyDate);

Assign the prettyDate to the necessary control.


This works better for me as sometimes I have troubles calling .datepicker('setDate', new Date()); as it messes if if i have the datepicker already configured with parameters.

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

$(function()
{
$('.date-pick').datePicker().val(new Date().asString()).trigger('change');
});

Source: http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerDefaultToday.html


Try this

$(this).datepicker("destroy").datepicker({
            changeMonth: false, changeYear: false,defaultDate:new Date(), dateFormat: "dd-mm-yy",  showOn: "focus", yearRange: "-5:+10"
        }).focus();

To pre-populate date, first you have to initialise datepicker, then pass setDate parameter value.

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

$(function()
{
$('.date-pick').datePicker().val(new Date().asString()).trigger('change');
});

Source: http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerDefaultToday.html


The setDate() method sets the date and updates the associated control. Here is how:

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

Demo

As mentioned in documentation, setDate() happily accepts the JavaScript Date object, number or a string:

The new date may be a Date object or a string in the current date format (e.g. '01/26/2009'), a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null to clear the selected date.

In case you are wondering, setting defaultDate property in the constructor does not update the associated control.


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

seemed to work, but there might be a better way out there..


Try this

$(this).datepicker("destroy").datepicker({
            changeMonth: false, changeYear: false,defaultDate:new Date(), dateFormat: "dd-mm-yy",  showOn: "focus", yearRange: "-5:+10"
        }).focus();

In order to set the datepicker to a certain default time (the current date in my case) on loading, AND then have the option to choose another date the syntax is :

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

Just thought I'd add my two cents. The picker is being used on an add/update form, so it needed to show the date coming from the database if editing an existing record, or show today's date if not. Below is working fine for me:

    $( "#datepicker" ).datepicker();
    <?php if (!empty($oneEVENT['start_ts'])): ?>
       $( "#datepicker" ).datepicker( "setDate", "<?php echo $startDATE; ?>" );
    <? else: ?>
       $("#datepicker").datepicker('setDate', new Date());   
    <?php endif; ?>
  });

$('input[name*="date"]').datepicker({
        dateFormat: 'dd-mm-yy',
        changeMonth: true,
        changeYear: true,
        beforeShow: function(input, instance) { 
            $(input).datepicker('setDate', new Date());
        }
    });

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-ui

How to auto adjust the div size for all mobile / tablet display formats? jQuery not working with IE 11 JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined Best Practice to Organize Javascript Library & CSS Folder Structure Change table header color using bootstrap How to get HTML 5 input type="date" working in Firefox and/or IE 10 Form Submit jQuery does not work Disable future dates after today in Jquery Ui Datepicker How to Set Active Tab in jQuery Ui How to use source: function()... and AJAX in JQuery UI autocomplete

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to jquery-ui-datepicker

How to format date with hours, minutes and seconds when using jQuery UI Datepicker? Jquery UI datepicker. Disable array of Dates How to set minDate to current date in jQuery UI Datepicker? Jquery DatePicker Set default date jQuery UI: Datepicker set year range dropdown to 100 years How to add/subtract dates with JavaScript? setting min date in jquery datepicker How do I clear/reset the selected dates on the jQuery UI Datepicker calendar? jQuery Date Picker - disable past dates Getting value from JQUERY datepicker