renat natanael renat natanael - 5 months ago 24
jQuery Question

jQuery Counter: Stop type when reach limit

I create a counter for text area and for now I success to count the length, but I want after it reach the limit, user can't type anymore.

How to make it stop able to type when reach the limit?

$('textarea').keyup(function () {
var max = 10;
var len = $(this).val().length;
var char = max - len;
if (len >= max) {
$(this).parent().find('.counter').text(char + '/'+max);
$(this).parent().find('.counter').css({"color":"red"});
}
else {
$(this).parent().find('.counter').text(char + '/'+max);
$(this).parent().find('.counter').css({"color":"#ccc"});
}
});


heres the jsfiddle
https://jsfiddle.net/5vf8pce3/

Answer

You can:

1) change keyup to keydown and return false;. Fiddle: https://jsfiddle.net/mrlew/5vf8pce3/4/

2) or use maxlength attribute (HTML5).

<textarea maxlength="10"></textarea>