Skip to content

Instantly share code, notes, and snippets.

@06b
Created November 12, 2012 14:49
Show Gist options
  • Save 06b/4059810 to your computer and use it in GitHub Desktop.
Save 06b/4059810 to your computer and use it in GitHub Desktop.
Detect inputs & textareas that use the required data annotation, attaches an asterisk to labels associated with them & replaces the legend indicating the asterisk's meaning.
/*
* jquery.requiredfields.js
* Copyright (c) 2012 Adrian D. Alvarez
* Licensed under the MIT, GPL licenses.
*/
(function ($) {
var requiredlegend = "Essential information is marked with an asterisk (<abbr title='Required' class='required'>*</abbr>)";
var requiredlegendset = false;
$("input,textarea").each(function (i) {
if ($(this).attr('data-val-required')) {
var id = $(this).attr('id');
var requiredlabel = $("label[for=" + id + "]");
var requiredlabeltext = $(requiredlabel).text();
$(requiredlabel).html(requiredlabeltext + " <abbr title='Required' class='required'>*</abbr> ")
if ($("fieldset:contains(" + $(this) + ")") && (requiredlegendset === false)) {
//Replace existing legend
$("fieldset").has(this).find('legend').html(requiredlegend);
requiredlegendset = true;
};
};
});
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment