Skip to content

Instantly share code, notes, and snippets.

@vohrahul
Created April 25, 2019 08:09
Show Gist options
  • Save vohrahul/44c06000e9ac80713e780b9ffe26f541 to your computer and use it in GitHub Desktop.
Save vohrahul/44c06000e9ac80713e780b9ffe26f541 to your computer and use it in GitHub Desktop.
$(function() {
CharLimitPlugin.Initialize('limit', 255);
});
/**
* CharLimit v1.0 - Character Limit Counter
* Author: Rahul Vohra
*/
var CharLimitPlugin = {
Initialize: function(selector, limitSize) {
this.AppendCharCount(selector, limitSize);
$('textarea.' + selector).on('keyup', function() {
el = $(this);
if (el.val().length > limitSize) {
el.val(el.val().substr(0, limitSize));
} else {
var existing = el.next('i').find('span.charCount');
$(existing).text(limitSize - el.val().length);
}
});
},
AppendCharCount: function(selector, limitSize) {
$("textarea." + selector).each(function() {
var limit = this.value.length;
limit = limit == 0 ? limitSize : (limitSize - limit);
var count = '<i><span class="charCount">' + limit + '</span> characters left.<i>';
$(count).insertAfter(this);
});
}
}
<textarea rows="4" class="limit">asdsadsadasdas</textarea>
<br>
<textarea rows="4" class="limit"></textarea>
<br>
<textarea rows="4" class="limit"></textarea>
<br>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment