开发者

Character Limit On Textbox

开发者 https://www.devze.com 2023-03-06 11:37 出处:网络
<input id=\"post\" type=\"text\" style=\"width:400px;\"/> You know when you go to a site, start typing in a textbox, and all o开发者_如何学编程f a sudden, your keyboard stops typing stuff beca
<input id="post" type="text" style="width:400px;"/>

You know when you go to a site, start typing in a textbox, and all o开发者_如何学编程f 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?


Use the maxlength attribute.

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


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

<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/

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

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


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');
    })
});


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);" />

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号