3
Using jQuery Datepicker and Dialog Box To Select Date Range
Web development, jquery
Tags: jquery
Share
Using a jquery datepicker in a jquery dialog box to select a date range is a handy, slick way of having users input dates. Date handling and validation in forms when input by the user can be tricky at best.
Here a modal dialog box will be used to allow the user to select a date range. That date range will be validated to ensure that it goes from a start date that is prior to the end date. Also, an alternate field will be populated by the datepicker that formats the dates in a specific way. This can be helpful if you are using the dates in a database query or other call that requires a certain format.
First we put a button to open the dialog box and the dialog box itself on the page:
<button id="selectDateRange">Select Date Range</button>
<div id="dialog" title="Select Date Range">
<div id="message"></div>
<form name="dateRange" id="dateRangeForm" action="index.cfm" method="post">
<label for="startdate">Start Date</label>
<input id="startdate" type="text" readonly /><input type="hidden" name="startdate"
id="start_alternate" />
<label for="enddate">End Date</label>
<input id="enddate" type="text" readonly /><input type="hidden" name="enddate" id="end_alternate"
/>
</form>
</div>
A message div is in the dialog box to send the user success or error messages related to their date selection. The input boxes are set to readonly so the user cannot type in a date; they must use the datepicker.
Also needed on the page is a little css to ensure that the datepicker is above the dialog box:
<style type="text/css">
.ui-datepicker
{
z-index: 1003;
}
</style>
Then the jquery to set the datepicker to the appropriate input box in the dialog box, specify the alternate field and format, and specify min and max dates:
$("#startdate").datepicker({altField: '#start_alternate',altFormat: 'yy-mm-dd',minDate: '-1y',maxDate: -1});
$("#enddate").datepicker({altField: '#end_alternate',altFormat: 'yy-mm-dd',minDate: '-1y',maxDate: -1});
The minDate is set to a year from today (user cannot go back more than a year) with ‘-1y’ and the maxDate is set to yesterday (user cannot pick today or a future date) with -1. Check the jQuery documentation on the datepicker min and maxDates for further explanation.
And, of course, the code for the button that opens our dialog box:
$('button#selectDateRange').click(function(){
$('#dialog').dialog('open');
});
The dialog box code does several things including:
- Closing the datepicker when the dialog closes
- Checking for values in the input boxes
- AJAX post to validate the date range
- Displaying a message to the user after validating the date range
- Sets the additional dialog close button functions
$(function(){
// jQuery UI Dialog
$('#dialog').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
close: function() {
$('#message').html('');
$('#dateRangeForm :input').each(function() {
$(this).val('');
});
$("#startdate").datepicker('hide');
$("#enddate").datepicker('hide');
},
buttons: {
"Submit": function() {
var errors = 0;
$('#dateRangeForm :input').each(function() {
if($(this).val() == ''){
$(this).prev().prev().css("color", "red");
$(this).prev().val('Click box and use calendar to enter date.');
errors++;
} else {
$(this).prev().css("color", "black");
}
});
if (errors == 0){
dataString = $('form').serialize();
$.ajax({
type: "POST",
url: "dateRange.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data == 'invalid'){
$('#message').html("<div class='errorMessage'>Date range is invalid.</div>");
} else {
$('#message').html("<div class='successMessage'>Date range is valid.</div>");
//location.reload();
}
}
});
return false;
}
},
"Close": function() {
$(this).dialog("close");
$('#message').html("");
$('#dateRangeForm :input').each(function() {
$(this).val('');
});
$("#startdate").datepicker('hide');
$("#enddate").datepicker('hide');
}
}
});
The daterange.php is pretty straightforward:
<?php $errormsg = "none"; $start_date = new DateTime($_POST["startdate"]); $end_date = new DateTime($_POST["enddate"]); if ($start_date > $end_date) $errormsg = "invalid"; echo json_encode($errormsg); ?>
Now, it entirely possible that you can validate the dates without a trip to the server; however, this example sets you up to use the dialog datepicker in more advanced processing or database calls on the server.
Usual recommended jQuery reading:
If this post helped you out, please consider donating to help pay the hosting fees. 100% of the donations go to the web host.
Further Reading:
5 Comments for Using jQuery Datepicker and Dialog Box To Select Date Range
HI
thanks
it is working
thom
February 22, 2010
HI. THanks for the script. I have been looking for this all day.
I have a problem where the second time I call the dialog box the datepicker is behind the dialog. Any ideas why or how the z-index would not be hte same both times?
Thom
@Thom
I don't know. I tried to replicate with my demo and couldn't. If you can send me a URL to a test page where this is happening, maybe I can take a look.
In the meantime, I updated my code a bit to clear the input boxes and error/success message. Nothing major.
thom
February 22, 2010
I would love to give you a URL, but it is on a password protected site so I do not really want to publish that here. I am calling this a little differently:
$('#addPayment').click(function() {
$('#dialog').dialog({
modal: true,
autoOpen: false,
width: 500,
height: 500,
close: function() {
$('#date').datepicker('hide')
}
}).load('/trip/<?=$trip_id?>/payments/addPayment/modal').dialog('open');
return false;
});
It seems like it is calling this function the initial time loaded, but not on subsequent times. The width is not even correct on the subsequent dialog boxes.
Leave a comment
« Positioning Multiple jQuery UI Dialogs | ColdFusion and Google Analytics: Getting Out What You Put In »

Gaurav Dhol
February 16, 2010