29

I have the following code, and I'm kind of stuck on what to do next. The idea is when you enter text into a text area a counter tells you how many characters you have left. Once you get to the max characters I want to stop allowing characters to be entered, or delete all the characters that were entered so there are only 10 characters in the text area. I know I have to put the code where it says alert("LONG"); but I'm not quite sure what.

var maxLen = 10;
        console.log("Start");
        $('#send-txt').keyup(function(){
            var Length = $("#send-txt").val().length;
            var AmountLeft = maxLen - Length;
            $('#txt-length-left').html(AmountLeft);
            if(Length >= maxLen){
                alert("LONG");
            }



        });
1
  • 2
    If the text is smal simply use an input text and it's maxlength attribute. If the text is long I think that this is not the best solution because if I copy/paste a text longer than the max it will be silently truncated. More than this, i can't have the ability to choose wich part to delete. You have to give a feedback to the user that something is going wrong. Commented May 7, 2015 at 10:32

17 Answers 17

42

All of these answers are a bit odd in that they try to do a little too much. A simpler and visually more pleasing way (because it shows the text quickly being cut off) - and with with less oddities that the previous example (note how it overwrites the final key?) - is to simply cut off the number of characters on keyUp to the number that's allowed.

var maxchars = 400;

$('body').on('keyup paste', 'textarea', function () {
    $(this).val($(this).val().substring(0, maxchars));
    var tlength = $(this).val().length;
    remain = maxchars - parseInt(tlength);
    $('#remain').text(remain);
});

Note that this then also works for pasting in text, as some of the examples above don't.

Example here: http://jsfiddle.net/PzESw/5/

3
  • I wrote a version which takes the "paste" event into account when right-click > paste is used, since this doesn't trigger keyup - jsfiddle.net/JCehq/1313. It's not perfect since the count is off when right-click > paste is used due to the .val() still being the prior value. If I think of a fix for this last bug I'll post it here. On a related note, some plugins I tried before looking at this question have the latter problem that I mentioned, e.g. ndpsoftware.com/show_char_limit.php Commented Mar 22, 2016 at 0:17
  • 1
    This is the most accurate answer, nice work. Couple things though, make sure you set var textlimit = 400; above the function if you want a 400 character limit for example. Also the line remain = parseInt(tlength); should be remain = textlimit - parseInt(tlength); instead if you want to show what's remaining out of your limit.
    – Tony M
    Commented Dec 12, 2018 at 2:35
  • 1
    Unlike the accepted answer, this is more elegant, and truncates pasted text. Commented Jan 11, 2020 at 19:46
32

Here it goes. Anything beyond character limit will be removed.

$('textarea').keypress(function(e) {
    var tval = $('textarea').val(),
        tlength = tval.length,
        set = 10,
        remain = parseInt(set - tlength);
    $('p').text(remain);
    if (remain <= 0 && e.which !== 0 && e.charCode !== 0) {
        $('textarea').val((tval).substring(0, tlength - 1));
        return false;
    }
})

Check working example at http://jsfiddle.net/JCehq/1/

10
  • like this solution but it chops the last char off when you are at the last position and move backwards Commented Mar 13, 2011 at 21:22
  • @steve I updated the answer. To prevent this from happening we need to add && e.which !== 0 && e.charCode !== 0
    – Hussein
    Commented Mar 13, 2011 at 22:14
  • 13
    Still there is trouble with copy-pasting. You can paste absolutely anything to textarea.
    – Alleo
    Commented Feb 22, 2012 at 21:28
  • 5
    Did anybody find a solution for copying into the textarea?
    – Codded
    Commented Dec 19, 2012 at 10:21
  • 4
    This is not a finished solution.
    – M H
    Commented Jul 28, 2015 at 16:48
4

Returning false and using .keypress() instead of .keyup() stops input once the length has been reached. Here's the example in a jsFiddle:

http://jsfiddle.net/p43BH/1/

Updated to allow backspace.

3
  • The problem with that is once you reach the limit you can't go back to update it.
    – Bill
    Commented Mar 13, 2011 at 21:01
  • Yeah, forgot about that. You need to use the event parameter to keypress() and check for backspace. I've updated the fiddle. Commented Mar 13, 2011 at 21:06
  • You can't go back using the arrow keys. return false; or preventDefault is not a good solution.
    – Hussein
    Commented Mar 13, 2011 at 21:19
3

Got it with this:

$("#div_id").prop('maxlength', '80');

I really dont know if there's something wrong with this solution, but it worked for me.

2
  • saved me from writing useless script
    – owais
    Commented Feb 13, 2019 at 10:01
  • This works but it still falls victim to the right-click-paste problem that the other solutions so far have. Commented Jan 11, 2020 at 20:00
2

A simple way to do this is to set the text in the textarea to a substring of the full amount. You can find an example here:

http://www.mediacollege.com/internet/javascript/form/limit-characters.html

1

If you change your js to look like this it should work for you:

var $txtLenLeft = $('#txt-length-left'); // lets cache this since it isn't changing
$('#send-txt').keydown(function(e) { //take the event argument
   var Length = $(this).val().length; // lets use 'this' instead of looking up the element in the DOM
   var AmountLeft = maxLen - Length;
   $txtLenLeft.html(AmountLeft);
   if(Length >= maxLen && e.keyCode != 8){ // allow backspace
      e.preventDefault(); // cancel the default action of the event
   }
});

You can see a working example here: http://jsfiddle.net/aP5sK/2/

3
  • 1
    Thanks, but the problem with this is you can't press the backspace or anything to change what you wrote
    – Bill
    Commented Mar 13, 2011 at 21:03
  • @Phil: Answer and example has been changed to allow backspace :) Commented Mar 13, 2011 at 21:07
  • if you use preventDefault you can't go back using the arrow keys.
    – Hussein
    Commented Mar 13, 2011 at 21:15
1

ehm, textarea maxlength is a valid attribute in html5 ? not supported in ie9, thats all.

w3nerds http://www.w3.org/TR/html-markup/textarea.html#textarea.attrs.maxlength

w3fools http://www.w3schools.com/tags/att_textarea_maxlength.asp

0

Here's a solution using HTML5 data attribute to automatically bind to all needed textareas:

$('textarea[data-max-length]').live('keypress', function(e) {
    if (String.fromCharCode(e.charCode || e.keyCode).match(/\S/) && $(this).val().length >= $(this).attr('data-max-length')) {
        e.preventDefault();
    }
});
0

I know this is a little late, but I just had to figure this out, too. I had to get it to work with UTF8 byte-lengths, and allow certain keypresses. Here's what I came up with:

checkContent = function (event) {

    var allowedKeys = [8,46,35,36,37,38,39,40];
    var contentLength = lengthInUtf8Bytes(jQuery(event.currentTarget).val());
    var charLength = lengthInUtf8Bytes(String.fromCharCode(event.charCode));

    if (charLength + contentLength > 20) {

        if(jQuery.inArray(event.keyCode, allowedKeys) == -1) {
            event.preventDefault();
        } 
    }
}

countLength = function(event) {

    var len = lengthInUtf8Bytes(jQuery(event.currentTarget).val());
    jQuery('#length').html(len);
}


lengthInUtf8Bytes = function(str) {
    var m = encodeURIComponent(str).match(/%[89ABab]/g);
    return str.length + (m ? m.length : 0);
}

jQuery(function(){jQuery("#textarea").keypress(function(event){checkContent(event)}).keyup(function(event){countLength(event)})});

You need to have a textarea with id #textarea and an element to display the current length with id #length.

The keypress event determines whether or not to allow the keypress. The keyup event counts the size of the data in the field after the keypress is allowed/prevented.

This code works with the following keys: home, end, pagedown, pageup, backspace, delete, up, down, left and right. It doesn't deal with pasting from the clipboard.

Hope someone finds it useful!

1
  • Forgot to metion, the max length in this example is 20, as you can see in the if statement. Commented Nov 28, 2011 at 8:52
0

Relying on keypress, keydown, keyup is a flawed solution because a user can copy and paste data into the textarea without pressing any keys.

To limit the length of text in a textarea with javascript regardless of how the data gets in there you must rely on a setInterval timer instead.

setInterval(function() {
if ($('#message').val().length > 250) {
    $('#message').val($('#message').val().substring(0, 250));
}}, 500);

Obviously, I'm assuming you have an id of message assigned to your textarea.

0

try this.

var charLmt = "200";//max charterer 
 $("#send-txt").keydown(function(){
   var _msgLenght = $(this).val().length;
   if (_msgLenght > charLmt) {
   $(this).val($(this).val().substring(0, charLmt));
  }
});
0
$("#message-field").on("keyup paste", function() {
  var $this, limit, val;
  limit = 140;
  $this = $(this);
  val = $this.val();
  $this.val(val.substring(0, limit));
  return $('#character-remaining').text(limit - $this.val().length);
});
0

Try this. Even works for copy paste from Keyboard:

$("#comments").unbind('keyup').keyup(function(e){
    var val = $(this).val();
    var maxLength = 1000;
    $('#comments').val((val).substring(0, maxLength));
    $("#comments_length").text($("#comments").val().length);
});
0

I find this works perfectly, and doesn't even flash the excess characters in the textarea before removing them, as a few other solutions do.

<h1>Add a comment:</h1>
<form>
    <textarea name="commentText" id="commentText"></textarea>
</form>
<br><span id="commentChars">1000</span> characters remaining

<script type="text/javascript">

    function checkChars(){
        var numChars = $('#commentText').val().length;
        var maxChars = 1000;
        var remChars = maxChars - numChars;
        if (remChars < 0) {
            $('#commentText').val($('#commentText').val().substring(0, maxChars));
                remChars = 0;
            }
        $('#commentChars').text(remChars);
    }

    $('#commentText').bind('input propertychange', function(){
        checkChars();
    });

    checkChars();

</script>
0

I think best way using maxlenght property + jquery keydown, keyup, paste events

// text input maximum lenght
$(document).on('keydown keyup paste', 'input[type=text]', function(e) {
  var textArea = $('input[type=text]').val(),
    textLenght = textArea.length,
    limit = $('textarea').attr('maxlength'),
    remain = 'left ' + parseInt(limit - textLenght) + ' chars';
  $('#remain-title').text(remain);
  if (textLenght > 500) {
    $('textarea').val((textArea).substring(0, limit))
  }
});

// tex area maximum lenght
$(document).on('keydown keyup paste', 'textarea', function(e) {
  var textArea = $('textarea').val(),
    textLenght = textArea.length,
    limit = $('textarea').attr('maxlength'),
    remain = 'left ' + parseInt(limit - textLenght) + ' chars';
  $('#remain-description').text(remain);
  if (textLenght > 500) {
    $('textarea').val((textArea).substring(0, limit))
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <label>Title</label>
  <p id="remain-title"></p>
  <input type="text" placeholder="Enter Title" maxlength="500"/>
</div>
<br>
<hr>
<br>
<div>
  <label>Description</label>
  <p id="remain-description"></p>
  <textarea placeholder="Enter custom description" rows="4" maxlength="500"></textarea>
</div>

See JSFiddle

0

In 2020 in most browsers limiting characters in textarea is supported by one helpful attribute maxlength check at w3chools

-1

I recommend to just add maxlength="10" to the textarea tag.

1
  • 1
    Welcome to StackOverflow. Please, edit and try for How to Answer, describe the effect of what you propose and explain why it helps to solve the problem, make the additional insight more obvious which you contribute beyond existing answers, the relevant advantage which your solution achieves, especially if the difference is so small and non-obvious. Compare to or contrast against stackoverflow.com/a/64258403/7733418 Consider taking the tour.
    – Yunnosch
    Commented May 18 at 3:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.