ROHIT MANDALAPU ROHIT MANDALAPU - 4 years ago 126
Javascript Question

How to prevent a textbox from taking input when it reaches limit in javascript

I am taking input from a text box and counting number of characters excluding spaces, special characters and new line (enter)in java script, but i am unable to restrict the user to enter any type of characters till he edits the text entered where as i was able to block complete keyboard.
I am using the code below, can you please suggest me some additions so that i can add the above functionality.



function countChars( countfrom, displayto ) {
var val = document.getElementById( countfrom ).value, len;
val = val.replace( /[^a-zA-Z0-9]/igm, "" );
len = val.length;

document.getElementById( displayto ).innerHTML = len;
if ( len >= 9 ) {
onkeydown = function( e ) {
e.preventDefault();
}
}
}

<textarea id="data" cols="40" rows="5"
onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br>
<span id="charcount">0</span> Characters entered.




Answer Source

preventDefault() is fine, but you should allow backspace and delete for the users to edit the text.

Check below snippet:

function countChars(countfrom, displayto) {
  var val = document.getElementById(countfrom).value;
  val = val.replace(/[^a-zA-Z0-9]/igm, "");
  var len = val.length;

  document.getElementById(displayto).innerHTML = len;

  onkeydown = function(e) {
    if (e.keyCode != 8 && e.keyCode != 46 && len >= 9)
      e.preventDefault();
  }

}
<textarea id="data" cols="40" rows="5" onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea>
<br>
<span id="charcount">0</span> Characters entered.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download