Associated Label/Input: a jQuery Plugin

Returns collections of labels or inputs based on their id and for attributes

Download…

Want to use “Duplicate/Remove” on your own website? No problem. You can download the full version.

Write Your Own…

Want to write your own plugin? I start all my plugins with a simple “skeleton” wrapper. Simply download my jQuery Plugin Skeleton and get started.

Run Code…

This page makes use of Run Code, a simple jquery plugin which converts your code examples to live behaviour.

Examples…

The default use of the plugin, returning a jQuery collection of labels, based on inputs.

$('#example-1 input').associatedLabelInput();

Returns a jQuery collection of associated inputs, based on given label collection.

$('#example-2 label').associatedLabelInput('input');

A practical example of potential use – basic validation – easily giving inputs and labels error classes. The example shows how the plugin works on single inputs/labels, when the input loses focus, as well as multiple input/labels when the form is submitted. The example only adds an error class to those which are marked as required.

$('#example-3 :input').filter('.required').bind('blur focus', {className: 'error'}, function(event){
	var $input, $label,
		value, className,
		$both;
		
	$input		= $(event.target);
	$label		= $input.associatedLabelInput();
	value		= $.trim($input.val());
	className	= (typeof event.data.className === 'undefined') ? 'error' : event.data.className;
	$both		= $input.add($label);
	
	if(value === '') {
		$both.addClass(className);
	}
	else {
		$both.removeClass(className);
	}
}).parents('form:first').bind('submit', {className: 'error'}, function(event){
	var $form, $input,
		$required, $missing,
		$label;
	
	className	= (typeof event.data.className === 'undefined') ? 'error' : event.data.className;
	$form		= $(event.target);
	$input		= $(':input', $form);
	$required	= $input.filter('.required');
	$missing	= $required.filter(function(){
		return ($.trim($(this).val()) === '');
	});
	
	if($missing.length > 0) {
		$label = $missing.associatedLabelInput();
		$missing.add($label).addClass(className);
	}

	event.preventDefault();
});