Search code examples
jqueryjquery-uijquery-ui-datepickermasking

Using jQueryUI Datepicker And Input Masking Together


First of all check live example . There is a mask for dates on text box. Also there is a jQueryUI datepicker. They are working very well but when i choose a date with datepicker, text box's mask is disappearing. I want to keep it. Any ideas?


Solution

  • I used this post. To create this fiddle.

    You can adjust the javascript to default to 00:00 if you don't want the current time as the default.

    date_obj = new Date();
    date_obj_hours = date_obj.getHours();
    date_obj_mins = date_obj.getMinutes();
    
    if (date_obj_mins < 10) { date_obj_mins = "0" + date_obj_mins; }
    
    if (date_obj_hours < 10) {date_obj_hours = "0" + date_obj_hours;}
    
    date_obj_time = "'"+date_obj_hours+":"+date_obj_mins+"'";
    
    $( ".datepicker" ).datepicker({ dateFormat: 'yy-mm-dd ' + date_obj_time });
    $(".datepicker").mask("9999-99-99 99:99");
    

    Thought I would add that this could be shortened to:

    date_obj = new Date();
    date_obj_hours = date_obj.getHours() < 10 ? "0" + date_obj.getHours() : date_obj.getHours();
    date_obj_mins = date_obj.getMinutes() < 10 ? "0" + date_obj.getMinutes() : date_obj.getMinutes();
    
    date_obj_time = "'" + date_obj_hours + ":" + date_obj_mins + "'";
    
    $(".datepicker").datepicker({ dateFormat: 'yy-mm-dd ' + date_obj_time });
    $(".datepicker").mask("9999-99-99 99:99");
    

    fiddle.