Max characters in textarea with jquery

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.


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/


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.


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/