How to prevent user to enter text in textarea after reaching max character limit

后端 未结 9 1471
盖世英雄少女心
盖世英雄少女心 2020-11-29 01:52

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

9条回答
  •  遥遥无期
    2020-11-29 02:44

    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);
    });
    

提交回复
热议问题