Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Datepicker Format Date on Manual Input

I have a jQuery datepicker with format: dd-MM-yyyy.

By default the datepicker converts dates such as 1-2-3 and 1-2-99 to 01-02-2003 and 01-02-1999 respectively. However, this is only the case when you press enter or choose the date from the datepicker. I tried to auto format the field when leaving the field by using:

$j('.datepicker').live('blur', function(){
    $j(this).datepicker('setDate', $j(this).datepicker('getDate'));
});

In this case I am using the utility function setDate and getDate of the Datepicker itself. This works when you enter the date by using your keyboard and using the TAB-key for example. However, the blur trigger also activates when you try to pick the date with your mouse. Therefore you have to choose the date twice with your mouse, because the first one the blur event sets the old value back.

Is there any event I am missing I can use?

Workaround

Not very elegant but it is a partial solution:

var timeout;
$j('#geboortedatum').live('keypress', function() {
    if(timeout) {
        clearTimeout(timeout);
        timeout = null;
    }
    timeout = setTimeout(formatDate, 1000);
});

function formatDate() {
    var gebdat = $j('#geboortedatum').val();
    var dashCount = gebdat.split('-').length - 1;
    if(dashCount == 2 && gebdat.length >= 5) {
        $j('#geboortedatum').datepicker('setDate', $j('#geboortedatum').datepicker('getDate'));
    }
}
like image 383
Serkan Avatar asked Dec 03 '22 04:12

Serkan


2 Answers

I just use the onClose event within datepicker istelf:

$(function(){
    var $myDate = $('#myDate');
    $myDate.datepicker({
      dateFormat: 'dd-mm-yy',
      onClose: function(dateText, inst) {
          $(this).datepicker('option', 'dateFormat', 'dd-mm-yy');                
    }
});

});​

http://jsfiddle.net/RpUSL/

like image 118
Brad Avatar answered Dec 20 '22 22:12

Brad


You could use the keypress event, but then you'd have to decide how much input constitutes something worth trying to auto-format.

Personally, I prefer to limit the input the textbox accepts. To that end, I'd recommend the jQuery Masked Input plugin.

like image 21
Matt Ball Avatar answered Dec 20 '22 21:12

Matt Ball