30

I want to prevent user to enter text in textarea once it reaches a max character limit. What was happening that when i reached to max limit then my text-area scroll-bar moved to top I somehow prevent this with this code.

jQuery(document).ready(function($) {
    $('textarea.max').keyup(function() {
        var $textarea = $(this);
        var max = 400;
        if ($textarea.val().length > max) {
            var top = $textarea.scrollTop();
            $textarea.val($textarea.val().substr(0, max));
            $textarea.scrollTop(top);

        }
    });
}); //end if ready(fn)

But i also want that after reaching max limit user unable to type anything in the textarea. Currently what happen that after reaching max limit if user press and hold the key, the characters are typing in the text area, although after releasing the button it come back to original text (i.e $textarea.val($textarea.val().substr(0, max)); ). But i want that once this condition become true

if ($textarea.val().length > max) {

user unable to type anything. I want that cursor vanishes from the textarea. But if user remove some text then cursor also available for user to type input again. How can I do it?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Basit
  • 8,426
  • 46
  • 116
  • 196

9 Answers9

58

The keyup event fires after the default behaviour (populating text area) has occurred.

It's better to use the keypress event, and filter non-printable characters.

Demo: http://jsfiddle.net/3uhNP/1/ (with max length 4)

jQuery(document).ready(function($) {
    var max = 400;
    $('textarea.max').keypress(function(e) {
        if (e.which < 0x20) {
            // e.which < 0x20, then it's not a printable character
            // e.which === 0 - Not a character
            return;     // Do nothing
        }
        if (this.value.length == max) {
            e.preventDefault();
        } else if (this.value.length > max) {
            // Maximum exceeded
            this.value = this.value.substring(0, max);
        }
    });
}); //end if ready(fn)
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • 3
    thanks, but after testing your code. Once it reaches the max limit it stops. I can't enter a word. But if then i press the backspace key then it doesn't work also. At-least user has the option to press backspace to remove the text and then again starting input. Btw this is the behavior that i want. User can't enter anything after reaching the maxlimit. :) How can i do it that user press the backspace key to remove and then again start entering text. Thanks – Basit May 02 '12 at 13:27
  • @Basit Updated answer. In Firefox, the nonprintable characters were not normalized to zero by jQuery. So, you have to manually exclude that ( http://www.asciitable.com/). – Rob W May 02 '12 at 13:34
  • Thanks Rob W:) But please tell me you used `(e.which < 0x20) `. It means all the characters like backspace, enter, tab, shift key which are non printable.Am i right? You also said that `nonprintable characters were not normalized to zero by jQuery`. What do you mean by not normalized to 0? Can you please explain it to me? – Basit May 02 '12 at 13:46
  • @Basit 0x20 is just the hex notation for 32. Any ASCII code below 32 is non-printable. jQuery's `event.which` is supposed to be consistent across all browsers. It doesn't. In Chrome, `0` is reported for backspace, in Firefox, 8 is reported. `event.which` for a `keypress` event represents the `event.charCode` property, which holds the ASCII char code of the pressed key (zero if not a character). – Rob W May 02 '12 at 13:51
  • HHmm ok but why backspace wasn't working when we used `if(!event.which){return}`. Why it is working after using `event.which<0x20`. In first case FF unable to find non-printable characters? So we tell FF explicitly by using `<0x20`? Am i right now? Can i use 32 here instead oh hex notation. Asking just for knowledge? Thanks – Basit May 02 '12 at 14:00
  • One thing more after reaching to maxlimit if i press enter key then it comes to next line. How can i prevent pressing enter key once in comes to max limit. You can also check this in your posted jsfiddle code. Thanks – Basit May 02 '12 at 14:12
  • @Basit `ENTER` has charCode 13. Just add this exception: `if (e.which < 0x20 && e.which != 13) {` – Rob W May 02 '12 at 14:42
  • 3
    It ll work when user types characters. But it is not working when user copy and paste the text – jeeva Sep 25 '13 at 11:40
  • Thanks! it works. But having issues in mobiles. Can you figure it out. – Naveen Gogineni Oct 12 '17 at 05:50
  • But this trims the last characters when I enter any character in between because of the substring – Juke May 10 '19 at 17:24
35
<textarea maxlength="400"> </textarea>

Use the above code to limit the number of characters inserted in a text area, if you want to disable the textarea itself (ie, will not be able to edit afterwards) you can use javascript/jquery to disable it.

KBN
  • 2,915
  • 16
  • 27
  • Hell @RobW, please check http://jsfiddle.net/ucb3n/ . EDIT:Tested on Firefox 12.0, Chrome 18.0, IE9. Did not work on IE9. – KBN May 02 '12 at 13:20
  • 2
    The `maxlength` attribute is new to HTML5, and not available to Internet explorer or Firefox < 4. Nevertheless, +1, because it's a nice solution. – Rob W May 02 '12 at 13:24
  • @RobW , thank you for that piece of info. And I honestly believe it's high time we all use updated browsers, other than of course the people who "NEED" it. – KBN May 02 '12 at 13:27
  • Please test the solution in Firefox Chrome and Safari This solution breaks in firefox version 51.0.1 (64-bit) – Parik Tiwari Feb 02 '17 at 19:55
  • Better and much simpler solution than the accepted answer. – Max Voisard Feb 05 '20 at 00:09
  • Be aware! Many modern browsers (in 2020) allow text beyond maxlength to be entered at first, but removes all characters past the maxlength when focus is lost causing potential text truncation https://caniuse.com/#feat=maxlength – denoise Aug 16 '20 at 07:47
  • simple solution ever – Santhosh Nov 17 '20 at 04:14
4

Keep it simple

var max = 50;
$("#textarea").keyup(function(e){
$("#count").text("Characters left: " + (max - $(this).val().length));
});

and add this in your html

<textarea id="textarea" maxlength="50"></textarea>
<div id="count"></div>

view example

2

Just write this code in your Javascript file.. But Need to specify the 'maxlength' attribute with textarea. This will work for all textarea of a page.

$('textarea').bind("change keyup input",function() {

        var limitNum=$(this).attr("maxlength");

        if ($(this).val().length > limitNum) {
            $(this).val($(this).val().substring(0, limitNum));
        }

    });
ViPuL5
  • 613
  • 7
  • 9
1

You could directly give maxlength to textarea to disable itself. But, you want to showing appropriate message then use keyup event for default behavior and textarea length for calculating charcter and display suitable message.

HTML

<div id="count"></div>
<textarea class="max"  maxlength="250" id="tarea"></textarea>
<div id="msg"></div>

jQuery

$(function(){
    var max = parseInt($("#tarea").attr("maxlength"));
  $("#count").text("Characters left: " + max);
    $("#tarea").keyup(function(e){
        $("#count").text("Characters left: " + (max - $(this).val().length));
    if($(this).val().length==max)
        $("#msg").text("Limit Reached....");
        else
        $("#msg").text("");
    });
});

Demo Fiddle

GuRu
  • 1,880
  • 3
  • 23
  • 32
0

You could use this plugin instead of trying to write your own. I've found that it works pretty well.

arb
  • 7,753
  • 7
  • 31
  • 66
0

You can keep your event as they are , and just use this library

Examples

// applying a click event to one element

Touche(document.querySelector('#myButton')).on('click', handleClick);

// or to multiple at once

Touche(document.querySelectorAll('.myButtons')).on('click', handleClicks);

// or with jQuery

$('.myButtons').on('click', handleClicks);
ProllyGeek
  • 15,517
  • 9
  • 53
  • 72
0

For those already using ES2015 in your browsers, here's an implementation using some of the answers above:

class InputCharacterCount {
  constructor(element, min, max) {
    this.element = element;
    this.min = min;
    this.max = max;
    this.appendCharacterCount();
  }

  appendCharacterCount(){
    let charCount = `<small class="char-counter help-block"></small>`;
    this.element.closest('.form-group').append(charCount);
  }

  count(event){
    this.element.attr('maxlength', this.max); // Add maxlenght attr to input element

    let value = this.element.val();
    this.element
      .closest('.form-group')
      .find('.char-counter')
      .html(value.length+'/'+this.max); // Add a character count on keyup/keypress

    if (value.length < this.min || value.length > this.max) { // color text on min/max changes
      this.element.addClass('text-danger');
    } else {
      this.element.removeClass('text-danger');
    }
  }
}

Usage:

let comment = $('[name="collection-state-comment"]');
let counter = new InputCharacterCount(comment, 21, 140);
$(comment).keyup(function(event){
  counter.count(event);
});
Gus
  • 6,545
  • 4
  • 36
  • 39
-1
 <script type="text/javascript">
        $(document).ready(function () {
            maxlength("TextArea1");
        });
        function maxlength(id) {
            $('#' + id).on('input propertychange', function () {
                CharLimit(this, 20);
            });
        }

        function CharLimit(input, maxChar) {
            var len = $(input).val().length;
            if (len > maxChar) {
                $(input).val($(input).val().substring(0, maxChar));
            }
        }
 </script>
jeff porter
  • 6,560
  • 13
  • 65
  • 123
  • 2
    Hi there, and welcome to Stack Overflow! Tip: when posting answers, it is a good idea to explain _why_ your answer is a good approach, and _how_ it works. – hat Feb 21 '19 at 12:27
  • Please include an explanation for your code and how it answers the question. – tshimkus Feb 21 '19 at 12:27