Domanda

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

È stato utile?

Soluzione

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!

Altri suggerimenti

As mentioned in the HTML specification, IDs must be unique. Your JavaScript code is failing because it conforms to this. There's no reason for it to continue checking elements after it's matched the first ID.

Once you have you IDs sorted, which is VERY important, use the following fiddle to help - http://jsfiddle.net/dXcLH/1.

In this fiddle, it just iterates through each textarea and sets a value in the list.

You could try something like this:

// tas is all your textareas
var tas= document.getElementsByName("textareas"), 
  // or document.getElementsByTagName("textarea")
i,arr=[];
for(i=0;i<tas.length;i++){
  arr.push({
    textareaName:tas[i].name,
    //rough word count
    wordCount:tas[i].value.split(/\b[^\d\w\-]+\b/ig).length
  }];
}
console.log(arr);

Check this code out in Chrome, press F12 and see the arr variable in the console, you can click on it to inspect it's values.

After you have set a class for all the textareas instead of an ID you could try the following:

 function countAllWords(){
   var result = 0;
   $(".edit").each(function(){
     var wordcount;
     wordcount = $(this).yourCountingFunction();
     result = result + wordcount;
   });
   return result;
 }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top