Scaling the length of a jQuery text area

I have the following code that works well, but the problem is that after exceeding 500 characters it starts letting the user enter (it accepts characters instead of restricting them!).

How can I change it? Is it possible to generalize this code so that it can process several text areas, for example, a function and just pass parameters?

$('#txtAboutMe').keyup(function () { var text = $(this).val(); var textLength = text.length;`enter code here` if (text.length > maxLength) { $(this).val(text.substring(0, (maxLength))); alert("Sorry, you only " + maxLength + " characters are allowed"); } else { //alert("Required Min. 500 characters"); } });" 
+4
source share
3 answers

You can try to determine maxLength, which will be used for comparison (if it is not defined, it is undefined, and each number is greater than undefined: why you never get the warning that I think):

 $('#txtAboutMe').keyup(function () { var maxLength = 500; var text = $(this).val(); var textLength = text.length; if (textLength > maxLength) { $(this).val(text.substring(0, (maxLength))); alert("Sorry, you only " + maxLength + " characters are allowed"); } else { //alert("Required Min. 500 characters"); } });" 
+5
source

You should not do this on keyup . Instead, try keypress . The problem is in keyup , the character is already running and written to the text field. Here is a good tutorial . Pay attention to the key press event.

 jQuery(function($) { // ignore these keys var ignore = [8,9,13,33,34,35,36,37,38,39,40,46]; // use keypress instead of keydown as that the only // place keystrokes could be canceled in Opera var eventName = 'keypress'; // handle textareas with maxlength attribute $('textarea[maxlength]') // this is where the magic happens .live(eventName, function(event) { var self = $(this), maxlength = self.attr('maxlength'), code = $.data(this, 'keycode'); // check if maxlength has a value. // The value must be greater than 0 if (maxlength && maxlength > 0) { // continue with this keystroke if maxlength // not reached or one of the ignored keys were pressed. return ( self.val().length < maxlength || $.inArray(code, ignore) !== -1 ); } }) // store keyCode from keydown event for later use .live('keydown', function(event) { $.data(this, 'keycode', event.keyCode || event.which); }); }); 
+8
source

Solution twice:

  • use the keydown event instead of keyup to catch the event before inserting the letter.
  • use preventDefault to stop the letter from pasting

     $('#txtAboutMe').keyup(function (e) {//note the added e to pass the event data var text = $(this).val(); var textLength = text.length;`enter code here` if (text.length > maxLength) { $(this).val(text.substring(0, (maxLength))); alert("Sorry, you only " + maxLength + " characters are allowed"); e.preventDefault(); return; } else { //alert("Required Min. 500 characters"); } 

    });

0
source

All Articles