-3

How can I get the number of characters typed into a textarea to put into one textbox, and the number of words from the textarea to put in the other, as I press Enter.

<textarea name="TextArea1" cols="20" rows="2"></textarea><br>

<input name="Text1" type="text" />Characters
<input name="Text1" type="text" />Words
FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
  • Just take `.value.length`? What part of the task do you have problems with? – Bergi Jan 14 '15 at 20:40
  • So what have you tried? Is something not working? SO Is not a coding service, we're not going to write this for you. – Tim Lewis Jan 14 '15 at 20:40
  • possible duplicate of [Show how many characters remaining in a HTML text box using JavaScript](http://stackoverflow.com/questions/12742595/show-how-many-characters-remaining-in-a-html-text-box-using-javascript) – Chris Forrence Jan 14 '15 at 20:42
  • Possible duplicate of: [textarea character limit](http://stackoverflow.com/questions/5533053/textarea-character-limit) – emerson.marini Jan 14 '15 at 20:42
  • I do not need a service. I tried looking for similar solutions but I couldn't find. Maybe I did not search well enough; however, I just am in need of someone to tell me how I should start out with the function. All I found was how to show the amount of characters remaining, as it shows underneath. –  Jan 14 '15 at 20:43
  • Okay thank you @MelanciaUK. I guess that was what I was looking for. Sorry for enraging recent posters. –  Jan 14 '15 at 20:44

1 Answers1

2

You would need to add an event listener which listens for the keyup (or keydown) event on the textarea.

Once you have that, you would need to check that the keyCode matches the return key (13).

After that, its a simple case of counting the length of the textarea value and splitting its value via the spaces in order to count the words.

var textarea = document.getElementById('textarea');
textarea.addEventListener('keyup', function (e) {
  if (e.keyCode === 13) {
    var characters = this.value.length;
    var words = this.value.split(' ').length;
    document.getElementById('characters').value = characters;
    document.getElementById('words').value = words;
    
  }
});
<textarea name="TextArea1" cols="20" rows="2" id="textarea"></textarea><br>

<input name="Text1" type="text" id="characters"/>Characters
<input name="Text1" type="text" id="words" />Words
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81