I want to prevent user to enter text in textarea once it reaches a max character limit. What was happening that when i reached to max limit then my text-area scroll-bar move
For those already using ES2015 in your browsers, here's an implementation using some of the answers above:
class InputCharacterCount {
constructor(element, min, max) {
this.element = element;
this.min = min;
this.max = max;
this.appendCharacterCount();
}
appendCharacterCount(){
let charCount = ``;
this.element.closest('.form-group').append(charCount);
}
count(event){
this.element.attr('maxlength', this.max); // Add maxlenght attr to input element
let value = this.element.val();
this.element
.closest('.form-group')
.find('.char-counter')
.html(value.length+'/'+this.max); // Add a character count on keyup/keypress
if (value.length < this.min || value.length > this.max) { // color text on min/max changes
this.element.addClass('text-danger');
} else {
this.element.removeClass('text-danger');
}
}
}
Usage:
let comment = $('[name="collection-state-comment"]');
let counter = new InputCharacterCount(comment, 21, 140);
$(comment).keyup(function(event){
counter.count(event);
});