0
votes

I have two fields in my form. One for check-in date, other for check-out date. I am using [bootstrap datepicker][1] for date selection. What I want to accomplish is that, once the check-in value has been set, minimal(startDate) check-out value will be check-in value + 1 day. This is my current code:

HTML:

        <form id="homeBookForm">
        <div class="inner-addon right-addon">
            <i class="fa fa-calendar" aria-hidden="true" id="checkInIcon"></i>
            <input type="text" class="form-control checkIn" 
            placeholder="Check-In">
        </div>
        <div class="inner-addon right-addon">
            <i class="fa fa-calendar" aria-hidden="true" id="checkOutIcon"></i>
            <input type="text" class="form-control checkOut" placeholder="Check-Out">
        </div>
        <button>Book Now</button>
    </form>

JS:

var date = new Date();
$('.checkIn').datepicker({
    format:'yyyy-mm-dd',
    todayBtn:true,
    autoclose:true,
    startDate:date
}).on('blur',function(){
    $('.checkOut').focus();
});
$('.checkOut').datepicker({
    format:'yyyy-mm-dd',
    todayBtn:true,
    autoclose:true,
    startDate:$('.checkIn').val()
});

Right now the code for checking the field works fine,but after autoclose happens the checkout field is just focused and datepicker doesn't even pop up.Anyone knows what I am doing wrong? Thanks in advance. :) [1]: http://bootstrap-datepicker.readthedocs.io/en/latest/index.html

1

1 Answers

3
votes

You can use date-picker's changeDate event to achieve all you want. Try changing your current implementation to this

var date = new Date();
$(".checkIn").datepicker({
    format: "yyyy-mm-dd",
    todayBtn: true,
    autoclose: true,
    startDate: date
  })
  .on("changeDate", function(e) {
    var checkInDate = e.date, $checkOut = $(".checkOut");
    checkInDate.setDate(checkInDate.getDate() + 1);
    $checkOut.datepicker("setStartDate", checkInDate);
    $checkOut.datepicker("setDate", checkInDate).focus();
  });

$(".checkOut").datepicker({
  format: "yyyy-mm-dd",
  todayBtn: true,
  autoclose: true
});

You don't need blur event anymore as date-picker's changeDate event will take care of setting focus to your check-out datepicker.

Check out the demo here https://codepen.io/anon/pen/ZrByVp?editors=1010