This JavaScript code snippet is used to add a button to a jQuery UI Datepicker for displaying "Today". The purpose of this button is to set the date to today and hide the Datepicker panel.
1-Html Input
<input type="text" id="datepicker" class="input-class" />
2-Java Script:
$(function () {
$("#datepicker").datepicker({
showButtonPanel: true, // Display button panel
dateFormat: "yy-mm-dd", // Date format
beforeShow: function (input) {
generateButton(input); // Call generateButton function before showing the Datepicker
},
onChangeMonthYear: function (yy, mm, inst) {
generateButton(inst.input); // Call generateButton function when month or year changes in Datepicker
},
});
// Function to generate the "Today" button
function generateButton(input) {
setTimeout(function () {
var buttonPane = $(input).datepicker("widget").find(".ui-datepicker-buttonpane");
var todayButton = $("<button>", {
text: "Today",
class: "ui-datepicker-clear ui-state-default ui-priority-primary ui-corner-all pull-left",
click: function () {
$(input).datepicker("setDate", new Date()).datepicker("hide"); // Set date to today and hide the Datepicker
}
});
buttonPane.empty(); // Clear all buttons in the button pane
buttonPane.append(todayButton); // Append the "Today" button to the button pane
}, 1);
}
// Function to change the date to today
$.datepicker._gotoToday = function (id) {
$(id).datepicker('setDate', new Date()).datepicker('hide').blur();
};});
Explanation:
This code utilizes jQuery and jQuery UI to create a Datepicker and apply it to the input element with id="datepicker".
The generateButton function is used to create and append the "Today" button to the Datepicker. This button, when clicked, sets the date to today and hides the Datepicker.
beforeShow and onChangeMonthYear are used to call generateButton before displaying and when the month or year changes in the Datepicker, respectively.
You can retrieve this code from here.
Make sure you have correctly included the paths to jQuery and jQuery UI in your page for this code to work properly.