views:

13103

answers:

8

I have a very simply 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.

+6  A: 
    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..

lucas
This works pretty well except for two things:1) I was kind of hoping to use jQuery method to get the current date, but maybe it doesn't matter.2) this solution produces a value exactly one month previous to today's date!
Marcus
OH - you're right! check it out - http://www.w3schools.com/jsref/jsref_obj_date.asp - month is 0-11 - you'll have to add 1.. curiously, getDate is 1-31, but getMonth is 0-11..
lucas
+3  A: 

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!

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

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

My browser did not recognise the asString() function.I did it like this: $(".date-pick").datepicker('setDate', new Date());
CiscoIPPhone
I think asString() should be toString().
gaoshan88
Kevin Luck's DatePicker and the Jquery UI DatePicker are two very different datepickers.
gamerzfuse
A: 

hi all I am using popup datepicker and have following code but it wont work $('#popupDatepicker').datepick().val(new Date().asString()).trigger('change');

anytips?

reverse
Not really an answer there. You just kinda copied the code from a previous answer as a question.
pauliephonic
A: 

i have a form with default values from a mysql database. after the page loads datepicker sets the current date for all my date fields :(( how can this be avoided? thanks in advance

zoly
+14  A: 

This is concise and does the job:

$(".date-pick").datepicker('setDate', new Date());
CiscoIPPhone
This is a MUCH nicer solution than the accepted solution!
Dan Diplo
A: 

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

Jeff Girard
A: 

replace .asString() with .toString()

Murali