Skip to content

Instantly share code, notes, and snippets.

@dieseltravis
Created April 21, 2009 14:48
Show Gist options
  • Select an option

  • Save dieseltravis/99176 to your computer and use it in GitHub Desktop.

Select an option

Save dieseltravis/99176 to your computer and use it in GitHub Desktop.
displaying char and word counts with jQuery
/*
sample HTML:
<div>
<p class="charStats wordStats">
<span class="curChars"><strong class="charVal">0</strong> chars</span>,
<span class="curWords"><strong class="wordVal">0</strong> words</span>
</p>
<textarea rows="2" cols="40" class="charCount wordCount"></textarea>
</div>
*/
// character/word counting
$(":text.charCount, textarea.charCount").each(function() {
var $this = $(this);
// get current number of characters
var charCount = $this.val().length;
// update characters
var $charCounter = $(".charStats .curChars .charVal", $this.parent());
$charCounter.html(charCount);
$(this).keyup(function() {
// get new length of characters
var newCharCount = $(this).val().length;
$charCounter.html(newCharCount);
});
});
$(":text.wordCount, textarea.wordCount").each(function() {
var $this = $(this);
// get current number of words, split on whitespace/punctuation
var wordRx = /[\s\x21-\x2F\x3A-\x40\x5B-\x60\x7B-\xBF]+/;
var wordCount = ($this.val().length > 0) ? $this.val().split(wordRx).length : 0;
// update characters
var $wordCounter = $(".wordStats .curWords .wordVal", $this.parent());
$wordCounter.html(wordCount);
$this.keyup(function() {
// get new length of words
var newWordCount = ($this.val().length > 0) ? $this.val().split(wordRx).length : 0;
$wordCounter.html(newWordCount);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment