Created
May 12, 2011 18:37
-
-
Save thinkt4nk/969163 to your computer and use it in GitHub Desktop.
Maximum Character Counter
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
(function($) { | |
/** | |
* Maximum Character Counter | |
* Author: Ryan Bales, Creative Anvil 2011 | |
* | |
* This plugin allows one to specify a container for a character counter element, set the maximum characters, and add an 'error' class to | |
* counter elements of offending text inputs | |
*/ | |
$.fn.jsCharacterCounter = function(options) { | |
// Set default values | |
var defaults = { | |
container_element : 'form', | |
max_characters : 400, | |
validate : false // true for js validation | |
} | |
// merge options with defaults | |
var options = $.extend(defaults,options); | |
// create object | |
this.characterCounter = {}; | |
$.extend(this.characterCounter,options); | |
this.getInputLength = function() | |
{ | |
return parseInt(this.val().length); | |
} | |
this.characterCounter.setCounter = function(length) | |
{ | |
var small_text = this.counter_element.find('small'); | |
small_text.text(length + ' Character(s) of ' + this.max_characters + ' limit'); | |
// set overflow class | |
if( parseInt(length) > parseInt(this.max_characters) ) { | |
small_text.addClass('error'); | |
} else { | |
small_text.removeClass('error'); | |
} | |
} | |
this.syncCounter = function() { | |
var value_length = this.getInputLength(); | |
this.characterCounter.setCounter(value_length); | |
} | |
// set-up validation if necessary | |
if( this.characterCounter.validate === true ) { | |
} | |
// encapsulate counter element | |
this.characterCounter.counter_element = $('<div/>') | |
.attr('id','comment-char-counter') | |
.append($('<small/>').text('0 of ' + this.characterCounter.max_characters + ' limit')) | |
.appendTo($(this.characterCounter.container_element)); | |
characterCounterObj = this; | |
this.syncCounter(); | |
// bind keyup event to input | |
this.bind('keyup',function() { | |
characterCounterObj.syncCounter(); | |
}); | |
return this; | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment