daterangepicker apply buttom not working properly

Chinmay235 picture Chinmay235 · Jul 28, 2015 · Viewed 12.8k times · Source

I am using daterangepicker please check my code here JSFIDDLE

I have set default date

"endDate": "08/03/2015",
"endDate": "08/03/2015",

And I have set an alert() for checking my code is working or not.

alert("New date range selected: '" + start.format('YYYY-MM-DD') + "' to '" + end.format('YYYY-MM-DD') + "'"); 

When I am clicking on book_date textbox range calendar is appearing. If i am changeing any date and clicking apply button its working fine. My alert() box is showing perfect. But when i click apply button without change any date. That time alert() box is not showing.

Also book_date is getting default date after clicking textbox and click anywhere in the page. So i don't want to put any default date without cilcking particular date. textbox should be blank while clicking ouside of calendar.

My Edited Code:

$('#book_date').on('apply.daterangepicker', function(ev, picker) {
    alert("New date range selected: '" + picker.startDate.format('YYYY-MM-DD') + "' to '" + picker.endDate.format('YYYY-MM-DD') + "'");
});

My textbox Calendar getting default value if i am not select any and clicking outside anywhere of the page.

Answer

Ash picture Ash · Jul 28, 2015

The callback function only executes when a new date is selected. As a possible work-around you could use the apply.daterangepicker event, which is triggered when the apply button is clicked:

$('#book_date').on('apply.daterangepicker', function(ev, picker) {
  var startDate = picker.startDate;
  var endDate = picker.endDate;
  alert("New date range selected: '" + startDate.format('YYYY-MM-DD') + "' to '" + endDate.format('YYYY-MM-DD') + "'");
});

See an example here.

Extended answer

There is no in-built way to prevent the dates being set when you click off the date picker, so you could try this:

Customise the hide function so the dates are cleared whenever the date picker is closed:

$('#book_date').on('hide.daterangepicker', function (ev, picker) {
    $('#book_date').val('');
});

Update the apply function to populate the dates field accordingly. So the dates are only set when the apply button is clicked:

$('#book_date').on('apply.daterangepicker', function (ev, picker) {
    var startDate = picker.startDate;
    var endDate = picker.endDate;  
    //MM/DD/YYYY format
    $('#book_date').val(startDate.format('MM/DD/YYYY') + ' - ' + endDate.format('MM/DD/YYYY'));
});

Updated demo here.