slandau
slandau

Reputation: 24102

Character Limit On Textbox

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

Upvotes: 13

Views: 29266

Answers (4)

Mani
Mani

Reputation: 71

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

Upvotes: 2

albert
albert

Reputation: 8153

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

Upvotes: 2

wesbos
wesbos

Reputation: 26317

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

Upvotes: 7

Town
Town

Reputation: 14906

Use the maxlength attribute.

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

Upvotes: 31

Related Questions