Javascript jQuery 限制输入框中的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12410868/
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-23 07:55:07  来源:igfitidea点击:

Jquery limit text in input box

javascriptjquery

提问by kukipei

I want to limit number of chars in input text field.

我想限制输入文本字段中的字符数。

Code I'm using:

我正在使用的代码:

function limitText(field, maxChar){
    if ($(field).val().length > maxChar){
       $(field).val($(field).val().substr(0, maxChar));
    }
}

Event is onkeyup. When I type some text in input field cursor stays on the end of text but focus is backed on start of the text so I can't see cursor.

事件是 onkeyup。当我在输入字段中输入一些文本时,光标停留在文本的末尾,但焦点回到文本的开头,所以我看不到光标。

What can be a problem.

有什么问题。

Browser is FF, on IE and chrome it is working correctly

浏览器是 FF,在 IE 和 chrome 上它工作正常

回答by Ties

you can also do it like this:

你也可以这样做:

<input type="text" name="usrname" maxlength="10" />

to achieve this with jQuery, you can do this:

要使用 jQuery 实现这一点,您可以这样做:

function limitText(field, maxChar){
    $(field).attr('maxlength',maxChar);
}

回答by thecodeparadox

Your code is working in FF. Here is slightly modified version of your code:

您的代码正在 FF 中运行。这是您的代码的稍微修改版本:

$('input.testinput').on('keyup', function() {
    limitText(this, 10)
});

function limitText(field, maxChar){
    var ref = $(field),
        val = ref.val();
    if ( val.length >= maxChar ){
        ref.val(function() {
            console.log(val.substr(0, maxChar))
            return val.substr(0, maxChar);       
        });
    }
}

Demo

演示