skip to Main Content

I have a textarea element in my HTML document where the user can input text. I have also added a span element to show the maximum allowed number of characters. I am using the following JavaScript code to update the counter as the user types:

This code js

span.innerHTML = textarea.value.length;
textarea.addEventListener("keydown", (event) => {
    span.innerHTML = textarea.value.length;
    if (textarea.value.length> 9 || !(event.keyCode>=65 || event.keyCode<=90)) {
    event.preventDefault();
    }
});

this code HTML

<body>
    <span>Maximum De Caractere est : <span id="span"></span> </span><br>
    <textarea id="textarea" cols="30" rows="10"></textarea>
    <script src="sc.js"></script>
</body>

The code is working as expected, except for one issue. When the user pastes text into the textarea, the length counter does not update correctly. Instead, it shows the length of the text before the paste operation. I want to either disable the paste option in the textarea or fix the length counting issue.

Can someone please suggest a solution or workaround for this problem? Thank you in advance!

2

Answers


  1. Consider using the input event for a better reflection of when the <textarea> value changes. This will ensure the character count is correct not only for pasting, but for when a user highlights multiple characters and deletes them.

    span.innerHTML = textarea.value.length;
    
    textarea.addEventListener("keydown", (event) => {
        if (textarea.value.length> 9 || !(event.keyCode>=65 || event.keyCode<=90)) {
          event.preventDefault();
        }
    });
    
    textarea.addEventListener("input", (event) => {
        span.innerHTML = textarea.value.length;
    });
     <span>Maximum De Caractere est : <span id="span"></span> </span><br>
     <textarea id="textarea" cols="30" rows="10"></textarea>
    Login or Signup to reply.
  2. In vanilla JS you can add a separate

    addEventListener("paste", (event) => {});
    # or:
    onpaste = (event) => {};
    

    to capture and react on the paste event… which can calculate the new input and if needed remove the last n of characters so that it meets your limit.

    Reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/paste_event


    You cannot disable the paste, but you ca set the textarea to readonly or disabled property (as a workaround)..

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search