0

I need to validate text area as following code,

my code as follows, here I need set maximum length as 10 and, if user trying to enter more than 10 need to prevent and if it is backspace or delete need to allow for deleting purpose. and also need to show remaining character count in a paragraph. But this code not working well. Its not preventing text input after 10.

<textarea id="txtxasa" class="message-content" onkeyup="Validate(event,this)"></textarea>
<p id="MsgContentRemainingLimit" class="message-character-limit">10 characters remaining</p>

function Validate(e,vald) {
    var code;
    var txtLength = vald.value.length;
    var remainingContent = 10 - txtLength;
    $('#MsgContentRemainingLimit').text(remainingContent);
    console.log(vald.value.length)

    if (!e) var e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which; 

    if (txtLength >=10 && (code != 8 || code != 46))
        return false;
}
thomsan
  • 433
  • 5
  • 19
  • Does this answer your question? [Count characters in textarea](https://stackoverflow.com/questions/5371089/count-characters-in-textarea) – devlin carnate Nov 24 '20 at 18:02
  • @devlincarnate No i need pure js here, without JQeury – thomsan Nov 24 '20 at 18:31
  • @devlincarnate Sir, I also need to prevent input typing more than 10. its not showing in that question. I need help to that also – thomsan Nov 24 '20 at 18:33

2 Answers2

0

Have you tried adding maxlength="10" to the textarea. I've done it and it works for me.

Manu Sampablo
  • 350
  • 5
  • 17
0

In Javascript you can try like this

let element = document.getElementById('input-name');
let countElem = document.getElementById('counter').innerHTML;

element.addEventListener('input', function() {

  let inputvalue = this.value;
  let maxLength = 10;

  //disable the input if reached the limit
  if (inputvalue.length > maxLength) {
    console.log('maximum character limit reached');
    this.disabled = true;
  }

  //count the numbers
  let count = parseInt(countElem, 10);
  document.getElementById('counter').innerHTML = count - inputvalue.length;

  if (inputvalue.length > count) {
    document.getElementById('counter').innerHTML = 0;
  }

});
<p>
  <input placeholder="First Name" id="input-name" name="input">
</p>

<p>remaining characters:</p><span id="counter" style="font-size:25px; font-weight:600;">10</span><br>

In Html5 you can also use the <input maxlength='10'> to limit characters only as a frontend validation. onkeyup in your code will not work if the user copy text and right click and paste them.

asans
  • 48
  • 1
  • 5