Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ciarancolgan/e0a6260c3b8ba9be645a2e78364f24d2 to your computer and use it in GitHub Desktop.
Save ciarancolgan/e0a6260c3b8ba9be645a2e78364f24d2 to your computer and use it in GitHub Desktop.
// Add this to a Js file that loads after jquery.validate.js.
// Override the 'focusInvalid' function from jquery.validate.js to a custom function which includes setting the focus for chosen dropdowns
$.validator.prototype.focusInvalid = function () {
if (this.settings.focusInvalid) {
try {
$(this.findLastActive() || this.errorList.length && this.errorList[0].element || [])
.filter(":visible")
.focus()
// manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find
.trigger("focusin");
// CUSTOM BIT - trigger focus on the first chosenJs select list in error
if (this.errorList.length) {
if ($(this.errorList[0].element).hasClass("chosen-select")) {
$(this.errorList[0].element).trigger('chosen:activate');
}
}
} catch (e) {
// ignore IE throwing errors when focusing hidden elements
}
}
}
@ciarancolgan
Copy link
Author

When using Chosen.js (https://harvesthq.github.io/chosen/) with Jquery UnobtrusiveValidation (typically with .NET MVC) - the focus wont be set to the first field in error if this is a Chosen Dropdown.
Override the jquery.validate.js function: 'focusInvalid' to add an additional check for this scenario.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment