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.php" 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.
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 (alternate javascript validation of date range included below)
- Displaying a message to the user after validating the date range
- Sets the additional dialog close button functions
$('#dialog').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
close: function() {
$('#message').html("");
$('#dateRangeForm :input').each(function() {
$(this).val('');
});
},
buttons: {
"Close": function() {
$(this).dialog("close");
$('#message').html("");
$('#dateRangeForm :input').each(function() {
$(this).val('');
});
},
"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.error == "invalid"){
$('#message').html("<div class='errorMessage'>Date range is invalid.</div>");
} else {
$('#message').html("<div class='successMessage'>Date range is valid.</div>");
}
} //end of success
}); //end of ajax
} //end of if(errors == 0)
} //end of Submit button function
} //end of buttons:
}); //end of dialog
Alternate method using javascript (no ajax call) to validate dates:
$('#dialog').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
close: function() {
$('#message').html("");
$('#dateRangeForm :input').each(function() {
$(this).val('');
});
},
buttons: {
"Close": function() {
$(this).dialog("close");
$('#message').html("");
$('#dateRangeForm :input').each(function() {
$(this).val('');
});
},
"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){
var start_date = new Date($("#startdate").val());
var end_date = new Date($("#enddate").val());
if(end_date < start_date){
$('#message').html("<div class='errorMessage'>Date range is invalid.</div>");
}else{
$('#message').html("<div class='successMessage'>Date range is valid.</div>");
}
} //end of if(errors == 0)
} //end of Submit button function
} //end of buttons:
}); //end of dialog
The daterange.php is pretty straightforward:
<?php
$start_date = new DateTime($_POST["startdate"]);
$end_date = new DateTime($_POST["enddate"]);
if ($start_date > $end_date){
$return_json = '{"error":"invalid"}';
}else{
$return_json = '{"error":"valid"}';
}
echo $return_json;
?>
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.
Recommended:
If this post helped you out, please consider donating to help pay the hosting fees. 100% of the donations go to the web host.

RSS
Twitter
One Trackback
[...] View Post Related PostsNo Related Post Posted in jQuery Tagged date range with jQuery, jquery datepicker, jquery dialog box [...]