0

Using bootstrap-datepicker. There are two textboxes for StartDate & EndDate. I'm trying to set validations when user changes the date in any of these two textboxes. At page load both boxes have current date.

Test Cases:
When user sets..
1. startDate beyond current date, set startDate=endDate
2. startDate beyond endDate, set endDate=startDate
3. endDate beyond current date, set endDate=current Date
4. endDate below startDate, set startDate=endDate

Case 1 fails. Say today is Jan 11, 2016 and I set the startDate as Jan 12, 2016, it doesn't change to Jan 11, 2011 but remains as Jan 12, 2016.

Also, Case 3 fails.

Is something wrong in my logic.

Here is the fiddle - http://jsfiddle.net/snh6eh9p/2/

JS:

function validateDates(dateType) {
  //dateType is to know if this function was fired by changing startdate or enddate
  //end-date must always be >= start-date
  var today = new Date();
  var startDate = new Date($(".txtStartDate").val());
  var endDate = new Date($(".txtEndDate").val());

  switch (dateType) {
    case 1:
    case "1":
      //if startDate is changed
      if (startDate > today) {
        setTriggerDates(endDate, 1); //set startDate=enddate         
      } else if (startDate > endDate) {
        setTriggerDates(startDate, 2); //set endDate=startDate
      }
      break;
    case 2:
    case "2":
      //if endDate is changed                    
      if (endDate > today) {
        setTriggerDates(today, 2); //set endDate=today
      } else if (endDate < startDate) {
        setTriggerDates(endDate, 1); //set startDate=endDate
      }
      break;
  }
}

function setTriggerDates(newDate, applyTo) {
  //applyTo determines, which textfield the value should be applied to.
  //if 1, then change value of txtStartDate,
  //if 2, then change value of txtEndDate  

  //populate date into the date fields
  var today = new Date(newDate);
  var dd = today.getDate();
  var mm = today.getMonth() + 1; //January is 0!
  var yyyy = today.getFullYear();

  if (dd < 10) {
    dd = '0' + dd
  }

  if (mm < 10) {
    mm = '0' + mm
  }

  today = yyyy + '-' + mm + '-' + dd;

  switch (applyTo) {
    case 1:
    case "1":
      $(".txtStartDate").val(today);
      break;
    case 2:
    case "2":
      $(".txtEndDate").val(today);
      break;
  }
}

1 Answer 1

1

updated your jsfiddle to fix the issue http://jsfiddle.net/snh6eh9p/4/.

Only change I did is call validateDates on hide event instead of changeDate event

$(".txtStartDate").datepicker()
.on("hide", function(ev) {
    validateDates(1);
});

$(".txtEndDate").datepicker()
.on("hide", function(ev) {
    validateDates(2);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.