I am building a date picker from scratch as a learning exercise. My date picker has two months side by side, and my question is, what does the jQuery look like for picking a start date and end date, allowing for the user to change their mind and have both dates on the same month, or on opposite months?
My HTML
<div class="calendar left">
<div class="calendar-days">
<div class="calendar-day" day="1">1</div>
<div class="calendar-day" day="2">2</div>
<div class="calendar-day" day="3">3</div>
<div class="calendar-day" day="4">4</div>
<div class="calendar-day" day="5">5</div>
...
...
</div>
</div>
<div class="calendar right">
<div class="calendar-days">
<div class="calendar-day" day="1">1</div>
<div class="calendar-day" day="2">2</div>
<div class="calendar-day" day="3">3</div>
<div class="calendar-day" day="4">4</div>
<div class="calendar-day" day="5">5</div>
...
...
</div>
</div>
Say the left month is August and the right month is September… they can choose start date August 5th and end date August 17th, or start date August 5th and end date September 22nd, or start date September 8th and end date September 12th, etc… there’s three scenarios.
Selecting the start date is obvious with a click event, and adding a selected class to that day. But how do I only allow two days to be selected at any given time across both calendars?
2
Answers
@Hordrist here is the UI... (I am good at UI but not yet JavaScript) I have it kind of working but the code is messy. I figured there is a common way to do this correctly rather than long if statements.
If I understand correctly, you want to limit date selection to two.
You can do so by verifying a condition inside your event handler :
Note that I used you idea of adding a selected class to the date.
This code does not really do any verification on whether start date is inferior to the end one, but instead lets the user select an end date first and a start date then, or the opposite
Hope this helped !