Mr.Stranger Mr.Stranger - 4 months ago 37
jQuery Question

Restrict time in jQuery timepicker dynamically?

I am having two fields in my form. One is date field which is using jQuery date picker and another one is jQuery time picker. Now the problem is, if i select the today's date in the date field, then the time picker should not shows the past time. For eg. if the time now is 17:00 hrs, then the timepicker should not shows the time before 17:00 hrs as selectable. Here is my code,

$(function() {
$( ".datepicker" ).datepicker({minDate:'0'});
$('.timepicker').timepicker();
});

$("#date").click(function(){
if($("#date").val()=='04/17/2012')
{
updatetimefortoday();
}
});![enter image description here][1]

function updatetimefortoday()
{
$('.timepicker').timepicker({
onHourShow: timepickerRestrictHours
});

function timepickerRestrictHours(hour)
{
if ((hour > 17))
{
return true;
}
return false;
}
}


Now the problem is if we call the function
updatetimefortoday()
on
document.ready
, it is showing the timepicker correctly. But if we do it on click of the date field as shown in the code it is not working.

enter image description here

This is the expected output after selecting the date.

Answer

After working a bit more with it, I came to the conclusion that the best way to do that is to always call the onHourShow function and validate the selected date in that function. I think this is better because the disabled hours are still visible to the user instead of blank cells.

$('#date').datepicker({
    minDate: 0
});
$('#time').timepicker({
    onHourShow: function( hour ) { 
        var now = new Date();
        // compare selected date with today
        if ( $('#date').val() == $.datepicker.formatDate ( 'mm/dd/yy', now ) ) {
            if ( hour <= now.getHours() ) {
                return false;
            }
        }
        return true;
    }
});‚Äč

here is a working example : http://jsfiddle.net/fgelinas/kUFgT/4/

As for the start and end hours problem reported by Aymad Safadi, I will see what I can do, this is definitely a bug.