Created
December 6, 2016 11:23
-
-
Save ciarancolgan/e0a6260c3b8ba9be645a2e78364f24d2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.