Linda Keating Linda Keating - 5 months ago 56
jQuery Question

Date Range Picker how to fire an event on entering a date

I'm using Dan Grossman's daterangepicker.

http://www.dangrossman.info/2012/08/20/a-date-range-picker-for-twitter-bootstrap/

Which is initialised in my web page, and now I'm trying to write the javascript that will be implemented once the date is entered by the user. However I have run into difficulty getting the daterangepicker to fire an event.

The code I'm using is

$('#dateRange').on('changeDate', function(ev){
alert(ev);
});


And here is the code that initialises the daterangepicker

$('#dateRange').daterangepicker({
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)],
'Last 7 Days': [moment().subtract('days', 6), moment()],
'Last 30 Days': [moment().subtract('days', 29), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
},
startDate: moment().subtract('days', 29),
endDate: moment()
},
function(start, end) {
$('#dateRange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
});


I've tried lots of different ways to listen for the event like
on.('blur')
or
on.('enter')
but nothing is firing the event for me.

Answer

this section is the callback function:

function(start, end) {
    $('#dateRange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
}

you can add any code you want in this function to execute when a user selects a date. you could even define a callback function yourself and pass it to the daterange picker method.

example:

function myCallback(start, end) {
    $('#dateRange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
    alert('hello world'); //etc, your code here
}
// attach daterangepicker plugin
$('#dateRange').daterangepicker(options, myCallback);

you also could even define your own custom event handler and trigger it in the callback as well.

example

$(document).on('myCustomEvent', function () {
    // your code here
});

$('#dateRange').daterangepicker({
// .. //
function(start, end) {
    $('#dateRange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
    $(document).trigger('myCustomEvent');
});