I need to display a list of dates between two given dates. For this, I use the jQuery UI Datepicker . The problem is that when I date range a second time, the previous list remains, and the new one is displayed below it.

For example, I choose:

 01/04/2016 — 05/04/2016 и получаю такой результат: 01/04/2016 02/04/2016 03/04/2016 04/04/2016 05/04/2016. 

Everything is normal here. However, when I again select the date range from 02/04/2016 to 07/04/2016 ,

I already get:

 01/04/2016 02/04/2016 03/04/2016 04/04/2016 05/04/2016 02/04/2016 03/04/2016 04/04/2016 05/04/2016 02/04/2016 03/04/2016 04/04/2016 05/04/2016 06/04/2016 07/04/2016 

instead of :

 02/04/2016 03/04/2016 04/04/2016 05/04/2016 06/04/2016 07/04/2016 

. To prevent this from happening, I have to reload the page, which is not very convenient. How can I get rid of this problem and make sure that the correct dates are displayed? Below is the code:

 $(function() { $( "#from" ).datepicker({ //defaultDate: "+1w", changeMonth: true, numberOfMonths: 1, onClose: function( selectedDate ) { $( "#to" ).datepicker( "option", "minDate", selectedDate ); } }); $( "#to" ).datepicker({ //defaultDate: "+1w", changeMonth: true, numberOfMonths: 1, onClose: function( selectedDate ) { $( "#from" ).datepicker( "option", "maxDate", selectedDate ); } }); }); <label for="from">From</label> <input type="text" id="from" name="from" onchange="dtrange()"> <label for="to">to</label> <input type="text" id="to" name="to" onchange="dtrange()"> <p id="result" onchange="dtrange()"></p> function dtrange(){ var start = $("#from").datepicker("getDate"); //yyyy-mm-dd var end = $("#to").datepicker("getDate"); //yyyy-mm-dd while(start <= end){ var mm = ((start.getMonth()+1)>=10)?(start.getMonth()+1):'0'+(start.getMonth()+1); var dd = ((start.getDate())>=10)? (start.getDate()) : '0' + (start.getDate()); var yyyy = start.getFullYear(); var date = dd+"/"+mm+"/"+yyyy; //yyyy-mm-dd document.getElementById("result").innerHTML += (date+'<br>'); start = new Date(start.setDate(start.getDate() + 1)); //увеличиваем дату на 1 } } 

    1 answer 1

    In the dtrange function before while

    do: document.getElementById("result").innerHTML = '';

    And then the result field will only add value to itself, without cleaning

     function dtrange(){ var start = $("#from").datepicker("getDate"); //yyyy-mm-dd var end = $("#to").datepicker("getDate"); //yyyy-mm-dd var result = document.getElementById("result"); result.innerHTML = ''; while(start <= end){ var mm = ((start.getMonth()+1)>=10)?(start.getMonth()+1):'0'+(start.getMonth()+1); var dd = ((start.getDate())>=10)? (start.getDate()) : '0' + (start.getDate()); var yyyy = start.getFullYear(); var date = dd+"/"+mm+"/"+yyyy; //yyyy-mm-dd result.innerHTML += (date+'<br>'); start = new Date(start.setDate(start.getDate() + 1)); //увеличиваем дату на 1 } }