25

I have a few areas on my site where I need to limit text input to X amount of characters and it's nice to show a number of spaces left while a user types in, like twitter does.

I found this jquery plugin; jquery max-length plugin

It does just what I need but it seems kind of like overkill, I am not sure the filesize but it looks like a lot of lines of code for such a simple task, do you think I would be better off using a non-jquery method? The reason I was thinking jquery was the way to go is because jquery is already included into all my pages UPDATE;

I just found this non-jquery method that does the exact same thing is is way smaller footprint, so would this be the better method?

<script language="javascript" type="text/javascript">
function limitText(limitField, limitCount, limitNum) {
   if (limitField.value.length > limitNum) {
    limitField.value = limitField.value.substring(0, limitNum);
   } else {
    limitCount.value = limitNum - limitField.value.length;
   }
}
</script>

You have 
<input readonly type="text" name="countdown" size="3" value="1000">
characters left.
JasonDavis
  • 48,204
  • 100
  • 318
  • 537

9 Answers9

55

Very simple in jQuery:

<textarea id="myTextarea"></textarea>
<p id="counter"></p>

<script type="text/javascript">
$('#myTextarea').keyup(function () {
    var left = 200 - $(this).val().length;
    if (left < 0) {
        left = 0;
    }
    $('#counter').text('Characters left: ' + left);
});
</script>

Substitute the 200 by whatever your limit is.

Note this does not limit the actual text input, it just counts down. You need to check server-side for the input length, this is just a visual helper.

As an aside, I don't think you even should try to limit the input length by denying any input when the limit is reached. It's a pain in the rear usability-wise and can't be relied upon anyway. A simple countdown and server-side checking is the best option IMHO.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 12
    To anyone implementing this, I'd recommend using `bind("propertychange input textInput")` over `keyup`. Those events will detect all forms of input, not just from the keyboard. – Andy E Oct 28 '11 at 20:27
  • 4
    Or instead of `.bind()`, as of jQuery 1.7, the `.on()` method provides all functionality required for attaching event handlers and is preferred. `$('#myTextarea').on("propertychange input textInput", funtion() {...});`. See accepted answer [here](http://stackoverflow.com/questions/8359085/delegate-vs-on) for some more info. – chrisjleu Jun 19 '12 at 09:24
  • Textarea cannot have an ID. – Charlie Apr 29 '14 at 23:18
  • 3
    @Charlie Do you have any proof for that assertion? https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes – deceze Apr 30 '14 at 05:35
  • I had read it somewhere and every time I use an HTML validation tool it always throws a fit about it. I know that it works but I was under the assumption that textarea was not allowed to have an ID. I Could be wrong and I should have asked 'Can a text area have an ID?'. – Charlie Apr 30 '14 at 17:06
  • @Charlie It can, at least in HTML 5. But AFAIK before that as well. – deceze Apr 30 '14 at 17:12
  • Stupid HTML Validation! – Charlie Apr 30 '14 at 17:20
  • To limit length of the input you can add this line directly below the left = 0; $(this).val($(this).val().substring(0, 200)); – Alan B. Dee Jan 08 '16 at 22:18
  • How to load the file displaying the `# counter` content? Sorry about the portuguese coment above – deleting May 17 '17 at 19:02
7

Sometimes you need to have more than one text area and want them addressed individually without having to code for each. This code dynamically adds the chars remaining to any having a maxLength attribute...

<script type="text/javascript">
$(document).ready(function(){
    $('textarea[maxLength]').each(function(){
        var tId=$(this).attr("id");
        $(this).after('<br><span id="cnt'+tId+'"></span>');
        $(this).keyup(function () {
            var tId=$(this).attr("id");
            var tMax=$(this).attr("maxLength");//case-sensitive, unlike HTML input maxlength
            var left = tMax - $(this).val().length;
            if (left < 0) left = 0;
            $('#cnt'+tId).text('Characters left: ' + left);
        }).keyup();
    });
});
</script>
<textarea id="myTextarea" maxLength="200">Initial text lorem ipsum blah blah blah</textarea><br><br>
<textarea id="mySecondTextarea" maxLength="500"></textarea><br><br>
<textarea id="textareaWithoutCounter"></textarea>
gordon
  • 1,152
  • 1
  • 12
  • 18
  • While CTRL-V keyboard pastes trigger the countdown, mouse pastes do not. I made the countdown text update a function and then call that with both keyup and blur: `$(this).keyup(function(){myFcn(this)}).blur(function(){myFcn(this)}).keyup();` and `function myFcn(argE){ var tId=$(argE).attr("id"); var tMax=$(argE).attr("maxLength"); var left = tMax - $(argE).val().length; if (left < 0) left = 0; $(argE).val( $(argE).val().substr(0,tMax) ); $('#cnt'+tId).text('Characters left: ' + left); }` Trying to handle the paste event got ugly for me – gordon Jun 06 '12 at 22:08
  • Of course real browsers like FireFox now recognize a textarea maxLength attribute :) – gordon Apr 22 '13 at 22:34
3

I've used Aaron Russell's simply countable jQuery plugin with success

Simple usage:

$('#my_textarea').simplyCountable();

Advanced usage:

$('#my_textarea').simplyCountable({
    counter: '#counter',
    countable: 'characters',
    maxCount: 140,
    strictMax: false,
    countDirection: 'down',
    safeClass: 'safe',
    overClass: 'over',
    thousandSeparator: ','
});
Ryan McGeary
  • 235,892
  • 13
  • 95
  • 104
  • thanks for the answer, I looking at many options but this plugin is really huge in size for such a simple task – JasonDavis Jan 26 '10 at 03:05
  • I've used this plugin also - very good! Personally I don't mind the file size as this plugin offers so much solid functionality for word and character counting/limiting. – Chris Jacob Jul 28 '11 at 06:36
2
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function()
        {
            $('#TestId').keyup(function(e)
            {
                var maxLength = 100;
                var textlength = this.value.length;
                if (textlength >= maxLength)
                {
                    $('#charStatus').html('You cannot write more then ' + maxLength + ' characters!');
                    this.value = this.value.substring(0, maxLength);
                    e.preventDefault();
                }
                else
                {
                    $('#charStatus').html('You have ' + (maxLength - textlength) + ' characters left.');
                }
            });
        });
    </script>
</head>
<body>
    <textarea id="TestId" cols="20" rows="8"></textarea><br />
    (Maximum characters: 100)<br />
    <span id="charStatus"></span>   
</body>
</html>
Raghav
  • 8,772
  • 6
  • 82
  • 106
2
 var max = 140;
        $("#spn").html(max+"  Remaining");
        $("#textarea").keyup(function () {
            var lenght1 = $("#textarea").val().length;
            var remaining = max - lenght1;
            $("#spn").html(remaining + "  Remaining");
            if (remaining < 0) { $("#spn").css('opacity', '0.4').css('color', 'red'); $("#comment").attr('disabled', 'disabled'); } else { $("#spn").css('opacity', '1').css('color', 'black'); $("#comment").removeAttr('disabled'); }
            if (remaining < 10) { $("#spn").css('color', 'red'); } else { $("#spn").css('color', 'black'); }

        });
  • When answering, to make it a good and helpful answer you need to also explain how to use your code. – ZygD Mar 29 '15 at 14:52
  • @ZygD This question has been answered so many times since I originally posted it in 2009!! IN any case it;s nice to see different approaches with the same outcome. I do like the idea of disabling a submit button when the textarea has too many characters! Based on this answer I just created this JSFiddle demo... http://jsfiddle.net/jasondavis/ht7qdL3m/ – JasonDavis Mar 29 '15 at 19:53
  • i am just trying to write a query like twitter i am also working on some different aspects of twitter like when characters goes in -ve value. text of textarea highlighted in red color – Mujahid Ali Apr 06 '15 at 16:23
1

I used jQuery and the answer by deceze and then tweaked it to give me a twitter-style countdown so that users could see by how much they had gone over and adjust their text accordingly. I also put it into its own function so I could call it from another function that sometimes populated the textarea automatically:

    function reCalcToText() {
        var left = 200 - $('.toText').val().length;
        if (left < 0) {
            $('#counter').text(left);
            $('#counter').addClass("excess");
        } else {
            $('#counter').text(left);
            $('#counter').removeClass();
        }
    }
    function onReady() {
                  $('#<%= toText.ClientID %>').keyup(function() {
            reCalcToText();
        });
    };
Community
  • 1
  • 1
Falkayn
  • 559
  • 3
  • 15
1

So I took @deceze version and added a bit of trick to make it:

  • show always and not only when the user starts typing,
  • show minus when the limit is over, and
  • add class - to color the text - when it is over the limit (extra css is needed for this of course)

    $(document).ready(function(){
        var left = 200
        $('#field_counter').text('Characters left: ' + left);
    
            $('#id_description').keyup(function () {
    
            left = 200 - $(this).val().length;
    
            if(left < 0){
                $('#field_counter').addClass("overlimit");
            }
            if(left >= 0){
                $('#field_counter span').removeClass("overlimit");
            }
    
            $('#field_counter').text('Characters left: ' + left);
        });
    });
    

For anyone needing the same as me :)

Christoffer
  • 7,436
  • 4
  • 40
  • 42
0

Using jQuery, assuming that you have a textarea with id field that you wish to limit to 100 characters, and another element with id chars-remaining to display the number of available characters:

var max = 100;
$('#field').keyup(function() {
    if($(this).val().length > max) {
        $(this).val($(this).val().substr(0, max));
    }
    $('#chars-remaining').html((max - $(this).val().length) + ' characters remaining');
});
bryan
  • 2,223
  • 1
  • 22
  • 19
0

Keep in mind that you have to account for NewLines being 2 characters.
I built upon the solutions provided here to the below code which accounts for new lines.

function DisplayCharactersLeft(idOfInputControl) {
    var maxNumberOfCharacters = $("#" + idOfInputControl).attr("maxLength");

    $("#" + idOfInputControl).on("input", function () {
        var currentText = $(this).val();
        var numberOfNewLines = GetNumberOfNewLines(currentText);

        var left = maxNumberOfCharacters - (currentText.length + numberOfNewLines);
        if (left < 0) { left = 0; }
        $("#" + idOfInputControl + "CharactersLeftCounter").text("Characters left: " + left);
    });

}    

function GetNumberOfNewLines(text) {

    var newLines = text.match(/(\r\n|\n|\r)/g);
    var numberOfNewLines = 0;
    if (newLines != null) {
        numberOfNewLines = newLines.length;
    }
    return numberOfNewLines;
}
trainer
  • 369
  • 4
  • 14