Did
Did

Reputation: 19

JavaScript code for counting the words input into an input box

I am supposed to write a function which can count the words in the text area but my code count only the first word, you can see the code here:

link to my code

var myTextareaElement = document.getElementById("myWordsToCount");
myTextareaElement.onkeyup = function wordcount(wor){
  var myTextareaElement =document.getElementById("myWordsToCount").value;
  var haveByNow = 0;
  for (var i = 0; i < wordcount.length; i++)
    if (wor[i] === " ") {
      haveByNow = +1;
    }
  haveByNow += 1;
  document.getElementById("wordcount").innerHTML = haveByNow;
}

Upvotes: 2

Views: 497

Answers (3)

Jacob
Jacob

Reputation: 78890

This line:

haveByNow = +1;

...is not the same as:

haveByNow += 1;

The former sets haveByNow to 1, the other increments. This is why you'd be seeing a result of 1 every time.

Another problem is this expression in your for loop:

wordcount.length

wordcount is the name of your function, and wordcount.length is the number of parameters of that function, which is not going to be what you want. myTextareaElement, which is the value of the input is what you want to get the length of:

for (var i = 0; i < myTextareaElement.length; i++) ...

Though as @itsgoingdown points out, there are better ways to get a word count.

Upvotes: 0

The Process
The Process

Reputation: 5953

Why not splitting on empty character that textarea value and get arraylength:
Check the snippet below

var myTextareaElement = document.getElementById("myWordsToCount");
myTextareaElement.onkeyup = function wordcount(wor) {

  var myText = this.value.trim();
  var wordsArray = myText.split(/\s+/g);
  var words = wordsArray.length;


  document.getElementById("wordcount").innerHTML = words;
};
<textarea id="myWordsToCount"></textarea>

<span id="wordcount"></span>

Upvotes: 1

isvforall
isvforall

Reputation: 8926

You have some typos and errors, see working code:

var myTextareaElement = document.getElementById("myWordsToCount");

myTextareaElement.onkeyup = function wordcount(wor){
    var words = myTextareaElement.value;
    var haveByNow = 1;
    for (var i = 0; i < words.length; i++) {
        if (words[i] == " ") {
            haveByNow += 1;
        }
    }
    document.getElementById("wordcount").innerHTML = haveByNow;
} 
<textarea id="myWordsToCount" rows="5" cols="60"></textarea><br>
The wordcount is: <span id="wordcount"></span><br>

Upvotes: 0

Related Questions