Simple jQuery Word and Character Counter For Text Box - Word Counter

Simple jQuery Word and Character Counter For Text Box - Word Counter
File Size: 2.19 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

Word Counter is a minimal jQuery script that adds a simple inline word and character counter to your textarea element.

How to use it:

1. Create a word and character counter next to your textarea element.

<textarea name="textCount" id="textCount"></textarea>
<p>You have <span id="wordCount">0 words</span> and <span id="charCount">0 characters</span></p>

2. Add the necessary jQuery library to your webpage.

<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>

3. The core function for the Word and Character Counter.

var wordCounter = {
  init: function() {
    this.DOM();
    this.events();
  },
  DOM: function() {
    this.textbox = $("#textCount");
    this.wordCount = $("#wordCount");
    this.charCount = $("#charCount");
  },
  events: function() {
    this.textbox.on("input", this.count.bind(this));
  },
  count: function() {
    var words = this.textbox.val().split(" "),
      chars = this.textbox.val();

    //DELETE EMPTY STRINGS
    for (var i = 0; i < words.length; i++) {
      while (words[i] === "") {
        words.splice(i, 1);
      }
    }
    //COUNT WORDS
    if (words.length === 1) {
      this.wordCount.text(words.length + " word");
    } else {
      this.wordCount.text(words.length + " words");
    }
    //COUNT CHARACTERS
    if (chars.length < 0) {
      words = [];
    } else if (chars.length === 1) {
      this.charCount.text(chars.length + " character");
    } else {
      this.charCount.text(chars.length + " characters");
    }
  }
}

4. Initialize the Word and Character Counter.

wordCounter.init();

This awesome jQuery plugin is developed by ChynoDeluxe. For more Advanced Usages, please check the demo page or visit the official website.