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

JavascriptJqueryJquery UiDateJquery Ui-Datepicker

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

Update: There are reports this no longer works in Chrome.

This is concise and does the job (obsolete):

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

This is less concise, utilizing chaining allows it to work in chrome (2019-06-04):

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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..

Solution 4 - Javascript

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.

Solution 5 - Javascript

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.

Solution 6 - Javascript

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!

Solution 7 - Javascript

This one worked for me.

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

Solution 8 - Javascript

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!) ;)

Solution 9 - Javascript

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

Solution 10 - Javascript

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

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

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

Solution 14 - Javascript

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

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

Solution 15 - Javascript

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

Assign the prettyDate to the necessary control.

Solution 16 - Javascript

Try this

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

Solution 17 - Javascript

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'));

Solution 18 - Javascript

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.

Solution 19 - Javascript

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarcusView Question on Stackoverflow
Solution 1 - JavascriptCiscoIPPhoneView Answer on Stackoverflow
Solution 2 - JavascriptRavi RamView Answer on Stackoverflow
Solution 3 - JavascriptlucasView Answer on Stackoverflow
Solution 4 - JavascriptSalman AView Answer on Stackoverflow
Solution 5 - JavascriptKirilleXXIView Answer on Stackoverflow
Solution 6 - JavascriptMarcusView Answer on Stackoverflow
Solution 7 - JavascriptCelestzView Answer on Stackoverflow
Solution 8 - JavascriptJeff GirardView Answer on Stackoverflow
Solution 9 - JavascriptGary MedinaView Answer on Stackoverflow
Solution 10 - JavascriptquocnguyenView Answer on Stackoverflow
Solution 11 - JavascriptmaozxView Answer on Stackoverflow
Solution 12 - JavascriptchispitaosView Answer on Stackoverflow
Solution 13 - JavascriptLes MizzellView Answer on Stackoverflow
Solution 14 - JavascriptNadirView Answer on Stackoverflow
Solution 15 - Javascriptgmail userView Answer on Stackoverflow
Solution 16 - JavascriptthejustvView Answer on Stackoverflow
Solution 17 - JavascriptAlpha2kView Answer on Stackoverflow
Solution 18 - JavascriptnikhilView Answer on Stackoverflow
Solution 19 - JavascriptView Answer on Stackoverflow