views:

72

answers:

1

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'));
    }
}
+1  A: 

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.

Matt Ball
But I want to allow the user to enter the shorter notation, like 1-2-3. keypress is perhaps worth trying in combination with a check whether length >= 5 and #dashes = 2 with a delay of 1 sec.
Serkan
@Serkan - if that works for you, then great. However, such shorter notation could really just be problematic since it's entirely nonstandard and ambiguous. Think about how many problems arise just because the date `1/2/2003` means "January 2nd, 2003" in some locales and "February 1st, 2003" in others.
Matt Ball
I completely agree with that. But it's for use in an intranet-site/application and we can assume that they are all using the day-month-year notation.
Serkan
@Serkan - fair enough. Intranet apps definitely operate under different assumptions. BTW, if you're looking to implement that check "length >= 5 and #dashes = 2 with a delay of 1 sec" then I definitely recommend the [throttle/debounce plugin](http://benalman.com/projects/jquery-throttle-debounce-plugin/) for the delay.
Matt Ball
Thanks for the tip!
Serkan