Get instant result on textarea as type


Try something like this but not work:

$(function() {
  var txt = $('#elementId:input').text(),
    charCount = txt.length,
    wordCount = txt.replace(/[^\w ]/g, "").split(/\s+/).length;
  $('#elementId:input').on('keypress',function() {
  $('#output').append("The text had " + charCount + " characters and " + wordCount + " words");

Your existing code has several issues:

  1. You only calculate txt, charCount, and wordCount one time (when the page loads), so on keypress you are only going to the same charCount and wordCount. You need to move your declarations to be inside the keypress callback function.

  2. You should actually be use the val() method instead of the text() method to get the text.

  3. By using keypress you run into two issues:

    • Your counts are always going to be behind
    • keypress will does not react to backspaces and other keystrokes in all browsers

    I suggest using the keyup event for it to have the latest count.

  4. Your replace will not correctly calculate the count of words if the string only has a single word and has a space on the end. I suggest using the trim method instead and leave your split regex the same.