How to display number count with a restrict number count of 255? Similar to Twitter, and without using Max length?

52 Views Asked by At
<html>
<head>
<script>

function showComment(count){ 
  //get the length of the comments. use document.getElementById.comments.length 
  let length = document.getElementById("showComment").length;
  //find the characters left by subtracting 255 - length 
  //condition if we go over 255
  //disable the field or just make the value equal to the first 255 characters. We can use substring method 
}    
    
</script>    
    
    
</head>
<body>

<form action="" method="post">    
<input type="text" name="fullname" id="fullname"  placeholder="fullname"><span class="err"></span><br>
<div id ="showcomment" >You have <span id="numleft"></span> characters of your 255 left!</div>        
<textarea id="comments OnKeyUp="showComment()></textarea>  
<input type="submit" name="submit" value="Enter"> 
    </form>
</body>    
</html>

I'm trying to display the characters I have left. I only have a total of 255 letters to spare and it should stop at 0. Also, I'm not suppose to use maxLength method.

1

There are 1 best solutions below

4
Unmitigated On

Read the value of the <textarea> element to access what was entered.

document.getElementById('comments').addEventListener('keyup', e => {
  e.target.value = e.target.value.substring(0, 255); // cut off at 255 chars
  document.getElementById("numleft").textContent = 255 - e.target.value.length;
});
<input type="text" name="fullname" id="fullname" placeholder="fullname"><span class="err"></span><br>
<div id="showcomment">You have <span id="numleft"></span> characters of your 255 left!</div>
<textarea id="comments"></textarea>
<input type="submit" name="submit" value="Enter">