I am trying to adapt a character counter to a word counted but with a space split that quits allowing type at the limit. I am using it with an Elementor form textarea. It works all the way until you get to 50 words and then everything disappears except for 50 characters. Not sure what I am doing wrong and too new to javascript to see the issue myself. Any help appreciated.
// #form-field-custom_essay
// #word_counter
var textInput = document.querySelector("#form-field-custom_essay");
var wordCounter = document.querySelector("#word_counter p");
var wordLimit = 50;
wordCounter.innerText = wordLimit + " Words Remaining";
textInput.addEventListener("keyup", function(){
var words = textInput.value.split(" ");
wordCounter.innerText = (wordLimit - words.length) + " Words Remaining";
if(words.length >= wordLimit) {
words = words.substring(0, wordLimit);
wordCounter.innerText = "0 Words Remaining";
wordCounter.style.color = "red";
} else {
wordCounter.style.color = null;
}
});
2
Answers
you can do that…
PS
wordLimit = 4
for quick testingsubstring function extracts characters, not words. You can try to disable typing on the textarea if the limit is reached.