jonthornton / Datepair.js

A javascript plugin for intelligently selecting date and time ranges, inspired by Google Calendar.
https://www.jonthornton.com/Datepair.js
359 stars 85 forks source link

Datepair not reacting when changing timepicker through code #17

Closed eljenso closed 10 years ago

eljenso commented 10 years ago

I am trying to change the values of paired time pickers through code, e.g. $('#start_picker').timepicker('setTime', new Date()). But somehow the paired picker will not update.

Updating by hand (typing the time into the input or selecting via dropdown) works flawlessly.

Here is the setup:

$('#start_picker').timepicker({
    'timeFormat': 'H:i',
    'step': 15,
    'scrollDefault': '8:00',
    'forceRoundTime': true
});

$('#end_picker').timepicker({
    'timeFormat': 'H:i',
    'step': 15,
    'scrollDefault': '8:00',
    'lang': {
        hr: 'Std',
        hrs: 'Std',
        mins: 'Min'
    },
    'forceRoundTime': true,
    'showDuration': true
});

$('#timePair').datepair({
    'defaultTimeDelta': defaultDuration * 60000 // milliseconds
});

// Delete input on bad input!
$('#start_picker').on('timeFormatError', function() {
    $('#start_picker').val('');
    $('#end_picker').val('');
});

$('#end_picker').on('timeFormatError', function() {
    $('#start_picker').val('');
    $('#end_picker').val('');
});
jonthornton commented 10 years ago

Datepair.js listens for a change event on the input fields to trigger updates. Timepicker's setTime function doesn't fire any events, so you need to trigger it in your code. This should do the trick:

$('#start_picker').timepicker('setTime', new Date()).trigger('change');
eljenso commented 10 years ago

Thank you, this works!

Why does Timepicker's setTime not fire any event?

jonthornton commented 10 years ago

It's so that you have the option of changing the input value without triggering event handlers. For example, Datepair.js takes advantage of this when it manipulates field values. Triggering manually is easy enough, which is why I didn't build it in as a method argument.