限制输入字段中的字符数

Fir*_*ous 19 html jquery webforms jquery-validate

我想使用jquery来限制可编辑div(或表单输入)中的字符数.

dku*_*mar 48

利用maxlengthinput标签

<input type="text" maxlength="20" /> 
Run Code Online (Sandbox Code Playgroud)


Ser*_*ets 20

支持此功能的浏览器Maxlength属性.
Javascript - 为其他人.

<input class="test-input" type="text" maxlength="12" />
<script>
$('.test-input').unbind('keyup change input paste').bind('keyup change input paste',function(e){
    var $this = $(this);
    var val = $this.val();
    var valLength = val.length;
    var maxCount = $this.attr('maxlength');
    if(valLength>maxCount){
        $this.val($this.val().substring(0,maxCount));
    }
}); 
</script>
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/tvpRT/

  • ...可能因为并非所有浏览器都支持内容可编辑...谢尔盖的回答是最好的:) (2认同)

小智 9

我认为这对你有用.

HTML

<input type="text" name="myText" id="myText" data-maxlength="10" />
Run Code Online (Sandbox Code Playgroud)

jQuery的

$('#myText').keyup(validateMaxLength);

function validateMaxLength()
{
        var text = $(this).val();
        var maxlength = $(this).data('maxlength');

        if(maxlength > 0)  
        {
                $(this).val(text.substr(0, maxlength)); 
        }
}
Run Code Online (Sandbox Code Playgroud)


Jul*_*les 6

如果你想使用jQuery的你可以写自己的东西或者只是使用现有的插件,比如这一个.

但我同意dku.rajkumar ...使用该maxlength属性有什么问题?

<input type="text" maxlength="15" />
Run Code Online (Sandbox Code Playgroud)

如果你是有史以来最大的JQuery粉丝,并且迫切想要maxlength立刻设置一个所有输入字段,请执行以下操作:

$(document).ready(function() {
   $('input[type="text"]').attr({ maxLength : 15 });
});
Run Code Online (Sandbox Code Playgroud)

请记住,虽然这种方法(JQuery one)不适用于那些(无论出于何种原因)禁用JavaScript的人.虽然标签的maxlength属性input适用于所有浏览器中的每个人.


Sel*_*gam 5

对于输入字段,您可以使用maxlength属性.如果您正在寻找div,请检查以下内容,

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

        <div id="editable_div" contentEditable="true" onclick="this.contentEditable='true';" >TEXT BEGIN:</div>
Run Code Online (Sandbox Code Playgroud)

编辑:您应该重写checkMaxLength函数以忽略制表符和换行符