Skip to content

Instantly share code, notes, and snippets.

@newbyca
Created July 17, 2012 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save newbyca/3132635 to your computer and use it in GitHub Desktop.
Save newbyca/3132635 to your computer and use it in GitHub Desktop.
custom Validity outputMode that handles Chosen <select> controls
(function($) {
function getIdentifier($obj) {
return $obj.attr('id').length ?
$obj.attr('id') :
$obj.attr('name');
}
$.validity.outputs.labellocal = {
cssClass:"error",
start:function() {
// Remove all the existing error labels.
$("." + $.validity.settings.cssClass)
.remove();
},
end:function(results) {
// If not valid and scrollTo is enabled, scroll the page to the first error.
if (!results.valid && $.validity.settings.scrollTo) {
location.hash = $("." + $.validity.outputs.labellocal.cssClass + ":eq(0)").attr('for');
}
},
raise:function($obj, msg) {
//if $obj has been Chosen-ified, point it at Chosen's ui surrogate
if($obj.hasClass('chzn-select')){
$obj = $('#' + getIdentifier($obj) + '_chzn');
}
//this is the positioning i need, you'll probably want something different
var pos = {};
pos.right = $(window).width() - ($obj.offset().left + $obj.outerWidth()) + 20;
pos.top = $obj.offset().top - 30;
var labelSelector = "." + $.validity.outputs.labellocal.cssClass + "[for='" + getIdentifier($obj) + "']";
// If an error label already exists for the bad input just update its text:
if ($(labelSelector).length) {
$(labelSelector).text(msg);
}
// Otherwize create a new one and stick it after the input:
else {
$("<label/>")
.attr("for", getIdentifier($obj))
.addClass($.validity.outputs.labellocal.cssClass)
.text(msg)
// In the case that the element does not have an id
// then the for attribute in the label will not cause
// clicking the label to focus the element. This line
// will make that happen.
.click(function() {
if ($obj.length) {
$obj[0].select();
}
})
.css(pos)
.hide()
.insertAfter($obj)
.fadeIn()
;
}
},
raiseAggregate:function($obj, msg) {
// Just raise the error on the last input.
if ($obj.length) {
this.raise($($obj.get($obj.length - 1)), msg);
}
}
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment