Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jqueryUI datepicker fires input's blur before passing date, avoid/workaround?

I have some validation on a text input bound to its blur event. I have a datepicker on this field (the version from jqueryUI), so when you click the field, datepicker shows up, then you click a date and it populates the date into the field as datepicker does. However, right before the date is entered it seems the input field gets its blur fired for some reason. It looks like focus goes away from the input before the date gets populated. So my validation gets fired right at the point when the user selects a date, before the date actually makes its way into the field, when it shouldn't. It should be running after the date gets put in. Does anyone know why the blur is is happening at that point or how to work around it?

like image 459
Purrell Avatar asked Nov 29 '09 00:11

Purrell


3 Answers

When the user clicks outside the input field (to choose a date), the input field will blur. There's no way around that. So, instead of triggering the validation on blur, use the datepicker's onSelect callback.

$('.selector').datepicker({
    onSelect: function(dateText) { /* validation here */ }
});

If you want to keep your onblur-events, you could postpone validation to allow for the datepicker to fill out the field before the validation fires, like this:

$('#myform input').blur(function () {
    setTimeout(function () { /* validation here */ }, 1);
});

Using setTimeout to handle concurrency-issues may look like a hack, but due to JavaScripts single-threaded nature, it works quite nicely. John Resig of jQuery-fame talks about it in this blogpost.

like image 62
Magnar Avatar answered Nov 15 '22 12:11

Magnar


You can try this :

$(".date-pick").datepicker({
...
onSelect: function() {
this.focus();
},
onClose: function() {
this.blur();
}
...
like image 8
user2955799 Avatar answered Nov 15 '22 14:11

user2955799


I found the only way to consistently get both the keyboard and the picker select events working was with the following code:

 $(".date-picker")
            .datepicker("option", "onSelect", function (dateText, inst) {
                // User Method
            })
            .change(function () {
                // User Method
            });

The problem with using just the blur event is that (when selecting) the datepicker fires the blur event on the input before the the value has been passed to it.

like image 6
kiwiaddo Avatar answered Nov 15 '22 13:11

kiwiaddo