Reputation: 21271
I'd like to add a word counter to a large text box (think blog editor) that increments with every word that I enter. (i.e. after I type "Hello" it would increment from 0 to 1 and after I write "world" after that it would increment to 2). I'd like to do this within a webpage but I'm happy to consider other options.
I have no idea how to do this. I think there would be a way to do this with Javascript but I know next to nothing about Javascript.
Could someone point me in the direction of figuring out how to do this?
Upvotes: 0
Views: 117
Reputation: 4374
Use this functionality on the onkeyup event for the textbox.
document.getElementById("inputbox").addEventListener("keyup",function(e){
// Get the inputs text.
var inputVal = e.srcElement.value;
var counter = 0;
// Check input isn't empty.
if(inputVal){
// Count individual letters.
var wordlist = inputVal.split(" ");
for(var i=0;i<wordlist.length;i++)
if(wordlist[i])
counter = counter+1;
}
// Then set your counter element.
document.getElementById("counter").value = counter;
});
Upvotes: 0
Reputation: 37365
I think a good idea to implement this is to check inputed letter (for example, onKeyUp event). If previous character was non-space and current is not a letter, then increment count. Detail: if previous character is non-letter, increasing should not be done (double spaces e t.c.)
When user is pressing Backspace
or Delete
key, similar check should be done. Key codes you can find here
The difficult thing with this counting 'on the fly' is to check 'non-key' input. For example, user can use Ctrl+Insert
combination to copy data from clipboard, or select text in the textbox and then press Del
key. That should be handled separately if there is real need to avoid whole value processing (which could be really huge)
Upvotes: 3