views:

417

answers:

1

Here's my problem, I have an input element in a form that is implementing jQuery.Autocomplete and jQuery.validate, all working normally except when I click an element in the autocomplete list to select it.

What happens is validation occurs before the autocomplete sets its value. Because validation occurs on onBlur, and you just clicked an item in the autocomplete list, blur fires and validation occurs a split second before the input is filled with its new value.

I wouldn't mind a double-validation if it was client side, but I happen to be executing an expensive remote ajax validation on this field, so I'd really like to solve this the right way.

My first thought is to proxy all validation onBlur events through a function that times out 10ms later, essentially flip flopping the event order. But, I think, that means tearing into the jQuery.Validate.js code, which I'd rather not do.

Any ideas?

+2  A: 

I was able to get this working but perhaps not as elegantly as I would have liked. Ideally I would have liked to call the prototype or defaults version of of onfocusout from within a timeout closure but I wasn't able to figure out how to reference it from that scope.

The approach that I took instead was to override the onfocusout method with its code copy/pasted into a timeout closure. The only other tweak was to change references from this to _this to work within the different scope of the timeout closure.

$("#aspnetForm").validate({
        success: "valid",
        onkeyup: "false",
        onfocusout:
            function(element) {
                //Delay validation so autocomplete can fill field.
                var _this = this;
                setTimeout(function() {
                    if (!_this.checkable(element) && (element.name in _this.submitted || !_this.optional(element)))
                        _this.element(element);
                    _this = null;
                }, 250);
            }
    });

Feel free to post improvements.

Snives
Sweeeeeeeeeet !
FALCONSEYE