Javascript 文本框的字符限制

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

Character Limit On Textbox

javascriptjqueryhtml

提问by slandau

<input id="post" type="text" style="width:400px;"/>

You know when you go to a site, start typing in a textbox, and all of a sudden, your keyboard stops typing stuff because you've reached the character limit?

您知道当您访问某个网站时,开始在文本框中输入内容时,突然间,您的键盘因为已达到字符数限制而停止输入内容吗?

How can I make that happen for this textbox for 140 chars?

我怎样才能为这个 140 个字符的文本框做到这一点?

回答by Town

Use the maxlengthattribute.

使用maxlength属性。

<input id="post" type="text" style="width:400px;" maxlength="140" />

回答by wesbos

Using the jQuery Limit plugin : http://jsfiddle.net/AqPQT/(Demo)

使用 jQuery 限制插件:http: //jsfiddle.net/AqPQT/(演示)

<script src="http://jquery-limit.googlecode.com/files/jquery.limit-1.2.source.js"></script> 
<textarea ></textarea>
<span id="left" />

and

$('textarea').limit('140','#left');

see also: http://unwrongest.com/projects/limit/

另见:http: //unwrongest.com/projects/limit/

If you are looking for a sans-jquery solution, just use the maxlength attribute.

如果您正在寻找 sans-jquery 解决方案,只需使用 maxlength 属性。

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

回答by Mani

Try this piece of code..

试试这段代码..

var limitCount;
function limitText(limitField, limitNum)
 {
   if (limitField.value.length > limitNum)
    {
     limitField.value = limitField.value.substring(0, limitNum);
    }
    else
    {
     if (limitField == '')
     {
       limitCount = limitNum - 0;
     }
     else
     {
       limitCount = limitNum - limitField.value.length;
     }
    }
   if (limitCount == 0)
     {
      document.getElementById("comment").style.borderColor = "red";
       }
   else
     {
       document.getElementById("comment").style.borderColor = "";
       }
 }
<input type="text" id="comment" name="comment" onkeyup="limitText(this,20);" onkeypress="limitText(this,20);" onkeydown="limitText(this,20);" />

回答by albert

function limitChars(textid, limit, infodiv) {
    var text = $('#'+textid).val(); 
    var textlength = text.length;
    if(textlength > limit) {
        $('#' + infodiv).html('You cannot write more then '+limit+' characters!');
        $('#'+textid).val(text.substr(0,limit));
        return false;
    }
    else {
        $('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
        return true;
    }
}

// Bind the function to ready event of document. 
$(function(){
    $('#comment').keyup(function(){
        limitChars('comment', 140, 'charlimitinfo');
    })
});