jQuery 限制输入字段中的字符数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8669268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:52:14  来源:igfitidea点击:

Limit number of characters in input field

jqueryhtmlwebformsjquery-validate

提问by Firdous

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

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

采纳答案by Selvakumar Arumugam

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

至于输入字段,您可以使用 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>

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

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

回答by dku.rajkumar

make use of maxlengthin inputtag

使用maxlengthininput标签

<input type="text" maxlength="20" /> 

回答by Serg Hospodarets

Maxlength attribute- for browser, that support this feature.
Javascript - for others.

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>

http://jsfiddle.net/tvpRT/

http://jsfiddle.net/tvpRT/

回答by JF Paris

This should work for you I think.

我认为这应该对你有用。

HTML

HTML

<input type="text" name="myText" id="myText" data-maxlength="10" />

jQuery

jQuery

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

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

        if(maxlength > 0)  
        {
                $(this).val(text.substr(0, maxlength)); 
        }
}

回答by Jules

If you want to make use of JQuery you can write something yourself or just use an existing plugin such as this one.

如果你想使用 JQuery,你可以自己编写一些东西,或者只使用一个现有的插件,比如这个插件。

But I agree with dku.rajkumar... What is wrong with using the maxlengthattribute?

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

<input type="text" maxlength="15" />

If you're the biggest JQuery fan everthough and desperately want to set a maxlengthto all of the input fields at once do something like:

如果您是有史以来最大的 JQuery 粉丝并且非常想一次maxlength为所有输入字段设置 a ,请执行以下操作:

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

Just keep in mind though that this method (the JQuery one) will not work for people who have (for any reason whatsoever) JavaScript disabled. While the maxlengthattribute of the inputtag works for everybody on all browsers.

请记住,尽管这种方法(JQuery 方法)不适用于那些(出于任何原因)禁用了 JavaScript 的人。虽然标签的maxlength属性input适用于所有浏览器上的每个人。

回答by Sang

Let's say it is form input.
you can do it with 'maxlength' attribute but if you say 'using jQuery',
here's the solution.

假设它是表单输入。
您可以使用“maxlength”属性来实现,但如果您说“使用 jQuery”,
这是解决方案。

$('input#limited').attr('maxlength', '3'); 

or you can check every keypress

或者你可以检查每个按键

$('input#limited').keypress(function() {
     /*
     check for 3 or greater than 3 characters.
     If you check for only greater than 3, then it will let
     you write the fourth character because just before writing,
     it is not greater than three.
     */
     if($(this).val().length >= 3) {
        $(this).val($(this).val().slice(0, 3));
        return false;
    }
});

回答by mkk

just use attribute called "maxlength". You can read more about input's attributes at w3 input

只需使用名为“maxlength”的属性。您可以在w3 input 中阅读有关输入属性的更多信息

回答by Hafsal Rh

$('#id').keypress(function(e) {
   var foo = $(this).val()
   if (foo.length >= 14) { //specify text limit
     return false;
   }
   return true;
});

回答by ask me

<input type="text" maxlength="20" id="alert_title"/>
$('#alert_title').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(typeof maxCount == "undefined"){
            $this.attr('maxlength',100);
        }
        if(valLength>maxCount){
            $this.val($this.val().substring(0,maxCount));
        }
    });