JQuery Override Datepicker to Return Today’s Date Example

How to override the JQuery Datepicker to return today’s date

JQuery Override Datepicker To Return Today's DateI support an ASP.net application that has multiple pages with fields that prompt for a date. All of our date input fields use the JQuery Datepicker calendar pop-up control to allow the user to select a date from the calendar.

The datepicker pop-up control can be defined to show several options (reference: JQuery Datepicker for details). One of those options is a button for today. When the today button is clicked the calendar control re-positions to the month containing today’s date. Many users wanted the today button to select and return today’s date to the date input field. This can be easily accomplished with a simple override.

Paste the following script in each page that loads the JQuery datepicker control, or better yet load it globally.

window.onload = function () {
	var o_gotoToday = $.datepicker._gotoToday;
	$.datepicker._gotoToday = function (id) {
		o_gotoToday.call(this, id);
		this._selectDate(id);
	}
}

Copy Code

A complete example

<!doctype html>
<html lang="en-US" prefix="og: https://ogp.me/ns#" class="no-js">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JQuery Datepicker Override</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script >
// override the today button
window.onload = function () {
	var o_gotoToday = $.datepicker._gotoToday;
	$.datepicker._gotoToday = function (id) {
		o_gotoToday.call(this, id);
		this._selectDate(id);
	}
}
// bind datepicker to our date field
$( function() {
	$( "#sampleDate" ).datepicker({
	changeMonth: true,
	changeYear: true,
	showButtonPanel: true,
	showOn: 'button',
	buttonText: 'Calendar'
	
	});
} );
</script>
</head>

<body>

<p>Sample Form</p>
<form name="sampleForm" action="DatepickerOverride.php" method="post">
<label>Date</label>
	<input type="text" name="sampleDate" id="sampleDate" size="10" maxlength="10" />
</form>

</body>
</html>

Copy Code


Click Here for a Working Example

References

JQuery
JQuery Datepicker

 


Leave a Reply

I appreciate and welcome your comments. Please keep in mind that comments are moderated according to my comment policy.
Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.