两次触发onchange函数

时间:2020-05-15 12:48:16

标签: javascript html jquery

我想将JQuery多日期选择器中的值用于不同的目的,但是由于某种原因,当我对所获得的值进行测试时,我两次都得到相同的结果。我想念什么吗?

我的代码:

$('.date').datepicker({
  multidate: true,
  format: 'dd-mm-yyyy'
});

function printDates() {
  var dates = document.getElementById("date_input").value;
  console.log(dates);

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js'></script>


<input type="text" name="dates" class="form-control date" id="date_input" placeholder="Pick the dates " onchange="printDates()">

2 个答案:

答案 0 :(得分:1)

https://bootstrap-datepicker.readthedocs.io/en/latest/events.html

使用引导日期选择器中提供的更改事件。

答案 1 :(得分:1)

使用changeDate代替onchange

$('.date').datepicker({
  multidate: true,
  format: 'dd-mm-yyyy'
})
.on('changeDate', function(e) {
       printDates(); // `e` here contains the extra attributes
    });
;

function printDates() {
  var dates = document.getElementById("date_input").value;
  console.log(dates);

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js'></script>


<input type="text" name="dates" class="form-control date" id="date_input" placeholder="Pick the dates " >