Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 981
Linda Keating Avatar asked Sep 01 '13 20:09

Linda Keating


2 Answers

From daterangepicker.com:

$('#daterange').on('apply.daterangepicker', function(ev, picker) {
    alert ('hello');
});
like image 172
Michele Avatar answered Sep 30 '22 15:09

Michele


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');
});
like image 28
Neil S Avatar answered Sep 30 '22 15:09

Neil S