skip to Main Content

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


  1. Chosen as BEST ANSWER

    enter image description here

    @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.


  2. If I understand correctly, you want to limit date selection to two.
    You can do so by verifying a condition inside your event handler :

    $(document).ready(function(){
        $(".calendar-day").on("click", function(){
        //To remove a selection if it is clicked once more
        if($(this).hasClass("selected"){
            $(this).removeClass("selected")
        }
        //To select a date and limit the number of selections
        else if($(".selected").length<2){
            $(this).addClass("selected");
        }
      })
    })
    

    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 !

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search