2

so I have a text area that I am trying to limit the word count on. So far I have this in the body

<textarea id="theTextArea" rows="10" cols="50"></textarea>

and this function

        function checkWordCount()  
                                   
        {
            var currStr = theTextArea.value;
            
            var tokens = currStr.split(" ");
            
            
            var numWords = tokens.length;
            
            wordCount.innerHTML = numWords;

            if (numWords > 24) {
                document.getElementById("theTextArea").disabled = true;
            }
        }

The problem with this is I need the user to be able to delete words and add new ones if they need to. This just disables it after 24 words and they can't modify it anymore

  • 1
    This makes for a bad user experience. Instead, show the remaining word count and a message indicating how many words left/how many words the user has gone over by. For example, type out a long comment on Stack Overflow. You'll see below the textarea an indicator for how many characters left/how far over you've gone. It's much nicer to complete your entire thought, then go back and selectively trim it down to meet the length requirements, then to be interrupted mid-thought. – user229044 Jul 31 '20 at 01:01
  • @meagar Spot on! – Always Helping Jul 31 '20 at 01:16
  • Something similar solved here: https://stackoverflow.com/a/17909970/5373542 – Fabrizio Valencia Jul 31 '20 at 01:22

1 Answers1

0

I agree with @meagar's comment, UX will be much better if you don't disable your textarea, but rather show error in case if there are too many words. Also, don't forget to add this check on the back-end.

In case if you still want to "disable" it - you should attach an event listener to textarea that would intercept keypresses and check if the user hit the word limit. If so - prevent the default behavior of keypress. This should allow him to delete words.

But before you do this, think about this case: I added 25 words. I want to replace one of them. So I want to add one and then delete one. I can't do this with your logic. Instead, show live verification, on every keypress, count words, and show this near textarea.

Maxim Mazurok
  • 3,856
  • 2
  • 22
  • 37
  • I already have a message that pops up saying they are out of words, but I just wanted a way to limit the words so they couldn't write any more. The word count display I have already in a different area of my code – EmmanoelD97 Jul 31 '20 at 01:16
  • In this case, see the second paragraph of my answer, it should help. – Maxim Mazurok Jul 31 '20 at 04:52