Skip to content

Instantly share code, notes, and snippets.

@replete
Created April 14, 2012 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save replete/2385061 to your computer and use it in GitHub Desktop.
Save replete/2385061 to your computer and use it in GitHub Desktop.
Text entry character count and truncate contenteditable
/* -------------------------------------- */
//Char count & truncate
var $charCount = $("[data-char-count]");
$charCount.each(function () {
var $this = $(this),
$charSelector = $($this.attr("data-char-count")),
charMax = $this.attr("data-char-count-max") || false;
$charSelector
.on("keyup", function() {
var $that = $(this),
charLength = $that.val().length,
charCountText = charLength;
if (charMax) {
charCountText = charLength + " / " + charMax; // + " characters used";
}
if( $that.val().length > parseInt(charMax) ) {
$this
.addClass("too-many-chars");
if ($this.attr("data-truncate")) {
var val = $charSelector.val();
$charSelector
.val( val.substring(0, parseInt(charMax)) );
}
} else {
$this
.removeClass("too-many-chars");
}
$this
.html(charCountText);
})
.trigger("keyup");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment