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

后端 未结 9 1476
盖世英雄少女心
盖世英雄少女心 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:32

    The keyup event fires after the default behaviour (populating text area) has occurred.

    It's better to use the keypress event, and filter non-printable characters.

    Demo: http://jsfiddle.net/3uhNP/1/ (with max length 4)

    jQuery(document).ready(function($) {
        var max = 400;
        $('textarea.max').keypress(function(e) {
            if (e.which < 0x20) {
                // e.which < 0x20, then it's not a printable character
                // e.which === 0 - Not a character
                return;     // Do nothing
            }
            if (this.value.length == max) {
                e.preventDefault();
            } else if (this.value.length > max) {
                // Maximum exceeded
                this.value = this.value.substring(0, max);
            }
        });
    }); //end if ready(fn)
    

提交回复
热议问题