1

I have code that displays the number of characters left to type.

This is my code:

<input type="text" name="title" value="" title="This is a required field." placeholder="title" maxlength="64" id="max_length_red" required>
<div class="max_length_red"></div>
<script>
(function(){
     document.addEventListener("keyup", function(event){
     if(event.target.matches("#max_length_red")){
     // get input value and length
     const value = event.target.value;
     const valueLength = event.target.value.length;
     // get data value
     const maxChars = parseInt(event.target.getAttribute("maxlength"));
     const remainingChars = maxChars - valueLength;
     if(valueLength > maxChars){
     // limit chars to maxChars
     event.target.value = value.substr(0, maxChars);
     return; //end function execution
     }
     event.target.nextElementSibling.innerHTML = remainingChars + " remainingChars";
     }
     })
})();
</script>

I am trying to change the code that will appear as soon as the page is loaded, because currently as long as I have not started writing text in the input the number of characters does not appear.

1 Answers1

1

You can make use of the DOMContentLoaded event which is fired as soon as the page is fully loaded and rendered.

From the MDN:

window.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM fully loaded and parsed');
});

A very simple solution could be:

<input type="text" name="title" value="Some value" title="This is a required field." placeholder="title" maxlength="64" id="max_length_red" class="limit-input" required>
<div class="max_length_red"></div>

<input type="text" name="title" value="Some other value" title="This is a required field." placeholder="title" maxlength="42" id="max_length_red2" class="limit-input" required>
<div class="max_length_red"></div>

<input type="text" name="title" value="Short" title="This is a required field." placeholder="title" maxlength="10" id="max_length_red3" class="limit-input" required>
<div class="max_length_red"></div>
<script>

function calculateChars(element) {
// get input value and length
   const value = element.value;
   const valueLength = element.value.length;
   // get data value
   const maxChars = parseInt(element.getAttribute('maxlength'));
   const remainingChars = maxChars - valueLength;
   if(valueLength > maxChars){
     // limit chars to maxChars
     element.value = value.substr(0, maxChars);
     return; //end function execution
   }
   element.nextElementSibling.innerHTML = remainingChars + " remainingChars";
}
(function(){
     document.addEventListener("keyup", function(event){
       if(event.target.matches(".limit-input")){
         calculateChars(event.target);
       }
     });
     
     // Here initialize the text with maximum chars allowed
     window.addEventListener('DOMContentLoaded', function () {
      const inputs = document.querySelectorAll('.limit-input');
      inputs.forEach((el) => calculateChars(el));
     });
})();
</script>
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
  • Now it works, but I have a new problem, if value="" in the input has a display text, it doesn't calculate it at first but only after writing the first letter, do you have any idea how to fix it? – gavriel adi Feb 16 '23 at 12:43
  • 1
    Sure, I have updated the snippet. All you need to do is to extract a function that does the calculation and invoke it on both events with a different argument – Sebastian Kaczmarek Feb 16 '23 at 12:46
  • 1
    You're welcome, glad I could help ;) If you found this helpful, consider accepting it as the best answer (the green tick on the left) – Sebastian Kaczmarek Feb 16 '23 at 12:52
  • 1
    Sure, you need to switch to classes instead of id. Check out my updated snippet – Sebastian Kaczmarek Feb 16 '23 at 13:33