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

Viewed 39788

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?

7 Answers

You can try this :

$(".date-pick").datepicker({
...
onSelect: function() {
this.focus();
},
onClose: function() {
this.blur();
}
...

I had the same problem as you, and Magnar's answer helped but did not completely answer the problem.

You have identified the underlying cause. The action of the user interacting with the calendar removes focus from the input field. This (in the case of jquery unobtrusive validation) will cause the onBlur event to fire, triggering the validation of that input field. At this point the value is still the previous value, until the user selects something.

Hence, building on Magnar's answer he states that you need to re-validate the input field onChange of the calendar. The most obvious way is to call $("form").valid(), however this validates the entire form.

A better way is to just validate the input field connected to the date picker, and you can trigger that by doing this:

$('#myform input').blur(function () {
    var that = this;
    setTimeout(function () {
        $(that).trigger("focus").trigger("blur");
    }, 100);
});

Now only your input field is validated, because you've faked the user clicking in and out of the input field.

Related