Restrict Date Range in jQuery UI DatePicker for two dates
Related Post:
- End Date should not be less than Start Date using jQuery Date Picker
- Few Interesting things with jQuery UI DatePicker setDate()
- jQuery UI DatePicker, IE 7 and an extra comma
Following things needs to be taken care.
- When Start Date is selected, then need to disable all the dates before selected start date + 4 days in end date datepicker. "minDate" option is our choice here.
- If end date is selected first, then disable all the dates after selected end date - 4 days in Start date datepicker. "maxDate" option is our choice here.
To implement this, write code in jQuery UI Datepicker "onSelect" event which gets called when date is selected.
$(document).ready(function () { var daysToAdd = 4; $("#txtFromDate").datepicker({ onSelect: function (selected) { var dtMax = new Date(selected); dtMax.setDate(dtMax.getDate() + daysToAdd); var dd = dtMax.getDate(); var mm = dtMax.getMonth() + 1; var y = dtMax.getFullYear(); var dtFormatted = mm + '/'+ dd + '/'+ y; $("#txtToDate").datepicker("option", "minDate", dtFormatted); } }); $("#txtToDate").datepicker({ onSelect: function (selected) { var dtMax = new Date(selected); dtMax.setDate(dtMax.getDate() - daysToAdd); var dd = dtMax.getDate(); var mm = dtMax.getMonth() + 1; var y = dtMax.getFullYear(); var dtFormatted= mm + '/'+ dd + '/'+ y; $("#txtFromDate").datepicker("option", "maxDate", dtFormatted) } }); });
The above jQuery code,
- First, takes the selected date and converts it in Date Object.
- And then adds/subtracts "daysToAdd" variable.
- And it sets formatted date to Datepciker.
If you also want to make sure that Start Date should be greater than end Date then set "minDate : 0" for from date datepicker.
Feel free to contact me for any help related to jQuery, I will gladly help you.