Limit number of characters in input field

前端 未结 9 875
Happy的楠姐
Happy的楠姐 2020-11-30 12:28

I want to use jquery to limit the number of characters in an editable div (or form input).

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 12:57

    As for input field you can use maxlength attribute. If you are looking for div, check the following,

            $(function() {
    
                $ ('#editable_div').keydown ( function (e) {
                    //list of functional/control keys that you want to allow always
                    var keys = [8, 9, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 144, 145];
    
                    if( $.inArray(e.keyCode, keys) == -1) {
                        if (checkMaxLength (this.innerHTML, 15)) {
                            e.preventDefault();
                            e.stopPropagation();
                        }
                    }
                });
    
                function checkMaxLength (text, max) {
                    return (text.length >= max);
                }
            });
    
            
    TEXT BEGIN:

    Edit: you should rewrite the checkMaxLength function to ignore tabs and newline

提交回复
热议问题