Search code examples
javascriptjquerytextareacounteronkeyup

Count words on multiple textareas on a html sheet


I have a html sheet that contains several textareas (100) and they all have the same id "edit".

My problem is that I want count all the words on each and everyone individually...

I have tried some pieces of code that I found on the internet that work fine on the first textarea but stop working on the second one...

I am a total newbie on javascript and I don't even know where to start. All the help is much appreciated.

Thanks


Solution

  • When you look up an element by ID, it will only ever return one, so your approach wont work for multiple elements. What you could do is iterate the id. For example, element 1's id = "edit1", element 2 = "edit2", element 100 = "edit100" and so on. This way, you could easily access all of them with a simple for loop:

    var rootID = "edit";
    var totalWordCount = 0;
    for (var i=0; i<100; i++) {
      var textElement = document.getElementById(rootID + i);
      var textBoxContents = textElement.value;
    
      // Count the words in one textbox.
      var textBoxWordCount = 0;
      // These are optional, they are there to account for new lines or double spaces
      // and will help make your word count more accurate.
      textBoxContents = textBoxContents.replace(/(^\s*)|(\s*$)/gi,"");
      textBoxContents = textBoxContents.replace(/[ ]{2,}/gi," ");
      textBoxContents = textBoxContents.replace(/\n /,"\n");
      // This splits up words and counts them based on whether there is a space 
      // between them or not. 
      textBoxWordCount = textBoxContents.split(' ').length;
    
      // Add this number of words to the total.
      totalWordCount += textBoxWordCount;
    }
    
    // totalWordCount now holds the total number of words in all your boxes!