Change the datepicker textbox value only if clicks OK in the confirmation box

Viewed 45

I want to check the selected date picker value. If the selected date picker and the previous value date difference is greater than 2, a confirmation box will display. And only if the user clicks OK from the confirmation box the value should change else it should display the previous value. The issue I'm facing is even if the user clicks on cancel the selected date is showing in the textbox.

$(function() {
var beforeChange = $("#planning_completion").val();
$("#planning_completion").on("changeDate", function () {
var selected = $(this).val();
var date1 = new Date(beforeChange);
var date2 = new Date(selected);
var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10); 
if(diffDays > 2){
    var didConfirm = confirm("Allocated date for this task is "+beforeChange+". Are you sure You want to change the date?");
    if(didConfirm == true){
        $("#planning_completion").val(selected);
} else {
    $("#planning_completion").val(beforeChange);
}
}        
});
});
1 Answers

You can use update whenever you change a date inside your datepicker and also i have added else part to update the value with previous date only if diff < 2.

Here is working demo code :

$(function() {
  $('#planning_completion').datepicker();
  //set today date
  $('#planning_completion').datepicker('setDate', new Date());
  var beforeChange = $("#planning_completion").val();
  $("#planning_completion").on("changeDate", function() {
    var selected = $(this).val();
    var date1 = new Date(beforeChange);
    var date2 = new Date(selected);
    var diffDays = parseInt((date2 - date1) / (1000 * 60 * 60 * 24), 10);
    console.log("diff"+diffDays)
    if (diffDays > 2) {
      var didConfirm = confirm("Allocated date for this task is " + beforeChange + ". Are you sure You want to change the date?");
      if (didConfirm == true) {
        $('#planning_completion').datepicker('update', selected); //added selcted value and update the same
      } else {
        $('#planning_completion').datepicker('update', beforeChange); //added beforeChange value and update the same

      }
    } else {
      //no change if less then 2 diff
      $('#planning_completion').datepicker('update', beforeChange);
    }
  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>

<input type="text" id="planning_completion" />

Related