jQuery UI Datepicker Form Submission onSelect

I was faced with the problem of submitting a form when selecting a date with the jQuery UI Datepicker. The solution is rather simple, but I think that explicitly stating it will be helpful to someone. In my case the form submitted to a .asp file that did something with the date and then came back. I know this can be done with AJAX, but this particular application changes a lot of the content on the main page … and to be honest I haven’t gotten to applying AJAX to the app. So! A form it is.

In the head section of your document link up your jQuery + UI + style sheet using a content delivery network (CDN) from Google. You could also host these files locally, but I prefer this way.

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/south-street/jquery-ui.css" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"</script>

Also in the head put the jQuery code below.

<script type="text/javascript">
	$(function() {
		$('#date').datepicker({
			showOn: 'both',
			buttonImage: "cal.png",
			buttonImageOnly: true,
			autoSize: true,
			onSelect: function (dateText, inst) {
				$(this).parent('form').submit();
			}
		});
	});
</script>

The important line is the onSelect command. Basically it submits the form in which the datepicker is contained. If you want to reference the form by name, you can instead use the line below. But I think the previous case is more general.

$('#frmDate').submit();

Next, throw in some CSS to format everything nicely.

<style>
	#ui-datepicker-div {
		font-size: 70%; /* Without this the datepicker looks huge! */
	}
	.ui-datepicker-trigger {
		vertical-align: middle;
	}
</style>

In the body of the document place this code. Change the action to be your code-behind page that does work with your form inputs.

<form id="frmDate" action="demo.html" method="post">
	<input id="date" name="date" type="text" />
</form>

That’s it! Hope this was of help to someone.

Cheers,
Mike