Search code examples
javascriptjquerybootstrap-datepicker

bootstrap datepicker on change


I have a bootstrap date picker which i want to alert when date is changed buit it is working something different

i am trying with simple jquery on.(change) event so it is executing two times one when user clicks on datepicker icon and another when user selects the date

CODE

$('#deliveryDate').datepicker({
  format: 'dd/mm/yyyy',
});
$("#deliveryDate").on("change", function(e) {
  alert("hi")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/css/gijgo.min.css" rel="stylesheet" type="text/css" />

<script src="https://cdn.jsdelivr.net/npm/[email protected]/js/gijgo.min.js" type="text/javascript"></script>
<div class=" col-lg-3">
  <label for="deliveryDate" id="commonHeader"> Date:</label>
  <input type="text" id="deliveryDate" name="deliveryDate" width="176" />
</div>

I have tried

$("#deliveryDate").on("dp.change", function(e) {
    alert('date');
});

but this one is not working

what i am trying to do is when user selects the date then alert should come not on click of datepicker


Solution

  • You can compare the values, and when there are chagnes, trigger the alert

    $("#deliveryDate").datepicker({
      format: 'dd/mm/yyyy',
    });
    
    var lastValue = null;
    
    $("#deliveryDate").on("change", function(e) {
    
      if(lastValue !== e.target.value){
        alert("hi");
        console.log(e.target.value);
        lastValue = e.target.value;
      }
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/css/gijgo.min.css" rel="stylesheet" type="text/css" />
    
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/js/gijgo.min.js" type="text/javascript"></script>
    <div class=" col-lg-3">
      <label for="deliveryDate" id="commonHeader"> Date:</label>
      <input type="text" id="deliveryDate" name="deliveryDate" width="176" />
    </div>