Skip to content

Instantly share code, notes, and snippets.

@halfzebra
Created July 13, 2015 22:30
Show Gist options
  • Save halfzebra/faa04a1535a705ae4cfc to your computer and use it in GitHub Desktop.
Save halfzebra/faa04a1535a705ae4cfc to your computer and use it in GitHub Desktop.
jQuery plugin that generates labels for inputs
/**
* A plugin to add labels for any kind of supported elements.
*
* @param settings
* @returns {jQuery}
*/
$.fn.createLabels = function(settings) {
var idAttr,
result,
$el,
$label,
$elColl = $(this),
methods = {
'checkIfHasLabel': function(id) {
result = false;
$label = $('label[for="' + id + '"]');
if ($label.length > 0) {
result = true;
}
return result;
},
'createLabel': function($current, id) {
$label = $('<label>').attr({
'for': id
});
if (settings.insert === 'after') {
$label.insertAfter($current);
} else if (settings.insert === 'before') {
$label.insertBefore($current);
}
}
};
$elColl.each(function(key, value) {
$el = $(value);
idAttr = $el.attr('id');
if (methods.checkIfHasLabel(idAttr) === false) {
methods.createLabel($el, idAttr);
}
});
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment