Reputation: 475
I have been trying to create a jQuery UI function for the datepicker, and after reading all the forums and snippets out there, I realize that a vast majority of answers have been deprecated and/or removed from jQuery 1.9.1.
Very Simply, I need to have the jquery datepicker
Display the datepicker with the options of buttons as well as be able to click on today which will automatically enter the date into my input field. For the life of me I can't figure this out and wanted to toss it to someone more knowledgeable in jQuery/ jQuery-UI.
$(function() {
$( "#date" ).datepicker(("setDate", new Date()){
showButtonPanel: true,
dateFormat: 'm-d-yy'
});
});
<input name="date" id="date" />
The inputed value should be in standard USA date format: i.e. 5/1/2013 or 12/31/2099.
As of now, the code doesn't select the current date, and obviously clicking today will only select today's date. I need it to automatically populate the input field. Thank you in advance for your help!
Upvotes: 2
Views: 10356
Reputation: 3059
I've created an EXAMPLE 1 for you that think would cover what you ask.
EDIT: Updated the EXAMPLE 2 and removed the initial date selection. Now it starts without any selected date.
HTML
<p>Date: <input type="text" id="datepicker" /></p>
JS (don't forget yo include jQuery UI 1.9.2 and jQuery )
var $datepicker = $("#datepicker");
$datepicker.datepicker({
showButtonPanel: true,
dateFormat: 'm-d-yy'
});
$datepicker.datepicker('setDate');
Upvotes: 2
Reputation: 11470
I think the problem is that most of us (and so did I) missunderstand the functionality of the "today" button. In fact it is just a button to highlight the current date and not to select it.
If you do want a behaviour where the user clicks on today and the datepicker selects the current date I'd recommend you to see a jsfiddle I created.
As this is not my work and I just did some research (working with datepicker at the moment too) I kindly refer to this solution which works perfect with jQuery 1.9.1 and jQuery UI 1.9.2.
This is the code which solves your issue
$.datepicker._gotoToday = function (id) {
var target = $(id);
var inst = this._getInst(target[0]);
if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
inst.selectedDay = inst.currentDay;
inst.drawMonth = inst.selectedMonth = inst.currentMonth;
inst.drawYear = inst.selectedYear = inst.currentYear;
} else {
var date = new Date();
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
// the below two lines are new
this._setDateDatepicker(target, date);
this._selectDate(id, this._getDateDatepicker(target));
}
this._notifyChange(inst);
this._adjustDate(target);
}
I hope this may help you :)
EDIT
To prepopulate your input field with the current date you need to use the setDate method. Updated fiddle
$('#datepicker').datepicker('setDate', new Date());
Upvotes: 2