Max characters in textarea with jquery
Asked Answered
B

17

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



        });
Beanie answered 13/3, 2011 at 20:39 Comment(1)
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.Chaechaeronea
A
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/

Agateware answered 13/3, 2011 at 21:12 Comment(10)
like this solution but it chops the last char off when you are at the last position and move backwardsSlocum
@steve I updated the answer. To prevent this from happening we need to add && e.which !== 0 && e.charCode !== 0Agateware
Still there is trouble with copy-pasting. You can paste absolutely anything to textarea.Fissile
Did anybody find a solution for copying into the textarea?Thunderbolt
Also there is a problem when we delete the contentProd
Can anyone explain this code please? Mainly 2nd, 3rd, 4th and 5th lines. Thanks.Hu
To update the number when you press backspace, you can use keydown instead of keypress eventAlligator
This is not a finished solution.Dumanian
return false after '$('textarea').val((tval).substring(0, tlength - 1));' will resolve the issueRelation
As of now, this doesn't truncate text when when pasting text longer than the max limit.Bezonian
A
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/

Amphichroic answered 28/3, 2013 at 19:50 Comment(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.phpCollette
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.Dripstone
Unlike the accepted answer, this is more elegant, and truncates pasted text.Bezonian
A
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/

Agateware answered 13/3, 2011 at 21:12 Comment(10)
like this solution but it chops the last char off when you are at the last position and move backwardsSlocum
@steve I updated the answer. To prevent this from happening we need to add && e.which !== 0 && e.charCode !== 0Agateware
Still there is trouble with copy-pasting. You can paste absolutely anything to textarea.Fissile
Did anybody find a solution for copying into the textarea?Thunderbolt
Also there is a problem when we delete the contentProd
Can anyone explain this code please? Mainly 2nd, 3rd, 4th and 5th lines. Thanks.Hu
To update the number when you press backspace, you can use keydown instead of keypress eventAlligator
This is not a finished solution.Dumanian
return false after '$('textarea').val((tval).substring(0, tlength - 1));' will resolve the issueRelation
As of now, this doesn't truncate text when when pasting text longer than the max limit.Bezonian
S
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.

Slocum answered 13/3, 2011 at 20:58 Comment(3)
The problem with that is once you reach the limit you can't go back to update it.Beanie
Yeah, forgot about that. You need to use the event parameter to keypress() and check for backspace. I've updated the fiddle.Slocum
You can't go back using the arrow keys. return false; or preventDefault is not a good solution.Agateware
P
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.

Peers answered 25/3, 2014 at 17:4 Comment(2)
saved me from writing useless scriptFlagrant
This works but it still falls victim to the right-click-paste problem that the other solutions so far have.Bezonian
E
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

Erythro answered 13/3, 2011 at 20:52 Comment(0)
K
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/

Karen answered 13/3, 2011 at 20:59 Comment(3)
Thanks, but the problem with this is you can't press the backspace or anything to change what you wroteBeanie
@Phil: Answer and example has been changed to allow backspace :)Karen
if you use preventDefault you can't go back using the arrow keys.Agateware
D
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

Duodecimal answered 9/4, 2013 at 13:7 Comment(0)
H
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();
    }
});
Heilman answered 24/3, 2011 at 12:45 Comment(0)
A
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!

Amado answered 28/11, 2011 at 8:51 Comment(1)
Forgot to metion, the max length in this example is 20, as you can see in the if statement.Amado
S
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.

Shame answered 26/5, 2014 at 1:46 Comment(0)
M
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));
  }
});
Medea answered 30/10, 2015 at 6:7 Comment(0)
I
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);
});
Interstellar answered 12/4, 2016 at 14:42 Comment(0)
V
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);
});
Volpe answered 4/8, 2016 at 3:19 Comment(0)
A
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>
Anzus answered 31/3, 2017 at 9:11 Comment(0)
C
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

Celery answered 9/6, 2018 at 16:32 Comment(0)
N
0

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

Noisome answered 8/10, 2020 at 8:12 Comment(0)
A
-1

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

Arlettearley answered 17/5 at 22:27 Comment(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 https://mcmap.net/q/478888/-max-characters-in-textarea-with-jquery Consider taking the tour.Cellular

© 2022 - 2024 — McMap. All rights reserved.