简体   繁体   中英

Javascript function to allow time input between range(08 - 15), or a default (in range) time in textbox on click

I use the dateTimePicker jQuery plugin from this site: http://xdsoft.net/jqplugins/datetimepicker

In my field I use date + time with a format of format:'d/m/YH:i' .

I have set allowTimes from 08:00 to 15:00 and works fine. However, if you choose a date, it automatically displays the current time (16.30) even though that the allowed times are between 08:00 to 15:00. How to set a default time, or the maximum time, anything between the allowed range? Thank you.

This is my code

$(document).ready(function(){

var d = new Date();
d.setDate(d.getDate() + 3);
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + '/' + (month<10 ? '0' : '') + month + '/' + (day<10 ? '0' : '') + day;

$('#datetimepicker').datetimepicker({
onShow: function(){
this.setOptions({ minDate: output });
},



onGenerate:function( ct ){
        $(this).find('.xdsoft_date.xdsoft_weekend')
            .addClass('xdsoft_disabled');
    },
    weekends:['01.01.2014','02.01.2014','03.01.2014','04.01.2014','05.01.2014','06.01.2014'],
    format:'d/m/Y H:i',
    minDate:'0',
    validateOnBlur: false,
    minTime:'08:00',
    maxTime:'15:00',
    dayOfWeekStart:'1',
    allowTimes:[
  '08:00', '08:30', '09:00', '09:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00'
 ]


});
});

That plugin has a onChangeDateTime event handler, so you could add something like this to your datepicker options:

onChangeDateTime:function(db,$input){
    var time = $input.val();
    // Now use some if logic to determine if the time has minutes
    // And if it does change the time to the closest appropriate.
}

This function should be called immediately after a date is picked, and if the current time from that date value is outside of your desired range, you can change it here and the user will never see the invalid current-time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM