Jason
Jason

Reputation: 1542

Jquery Validate Focus to Hidden field on invalid

Using jquery validate to validate hidden fields due to using typeahead (setting a hidden field on select) and rateit plugin (setting a hidden field on select)

They are validating fine and I have the error message displaying and clearing correctly.

The issue is that if one of those fields is the first invalid field it doesn't focus because the element is hidden.

Anyone know a way around this?

thanks

Upvotes: 0

Views: 3871

Answers (2)

Jason
Jason

Reputation: 1542

Ended up doing it this way and it's working well. I added an attribute to my hidden inputs

Ex:

<input name='whatever" class="required" focusID="ID_TO_FOCUSTO" value="">

Then added this to validate. If it's visible it just focused to that element like normal. If not then it focuses to the ID of the attribute focusID on the hidden input.

    invalidHandler: function(form, validator) {
        var errors = validator.numberOfInvalids();
        if (errors) {
            if($(validator.errorList[0].element).is(":visible"))
            {
                $('html, body').animate({
                    scrollTop: $(validator.errorList[0].element).offset().top
                }, 1000);
            }
            else
            {
                $('html, body').animate({
                    scrollTop: $("#" + $(validator.errorList[0].element).attr("focusID")).offset().top
                }, 1000);
            }
        }
    }

Upvotes: 4

Gonzalo
Gonzalo

Reputation: 2876

You can do a custom rule for Typeahead field, validating the hidden field containing the id value. So if it is invalid, focus will be put on the typeahead field.

    jQuery.validator.addMethod("myCustomValidate", function() {
        //check if hidden field has a value
        return $("#hiddenFieldId").value);
    }, "You must be select a item");


$('validatorElement').validate({
    ignore: "",
    rules : {
        typeaheadElement: { myCustomValidate: true }
    }
});

Upvotes: 1

Related Questions