Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit the number of characters entered in a text area

Here's my attempt at limiting the number of characters entered into a text area:

var limit = 255;
var txt = $('textarea[id$=txtPurpose]');

$(txt).keyup(function() {
    var len = $(this).val().length;
    if (len > limit) {
        //this.value = this.value.substring(0, 50);
        $(this).addClass('goRed');
        $('#spn').text(len - limit + " characters exceeded");
        return false;
    } else {
        $(this).removeClass('goRed');
        $('#spn').text(limit - len + " characters left");
    }
});

However, it doesn't work very well. How can I prevent a user from entering text once a certain limit has been reached, say 255 characters?

like image 858
Nick Kahn Avatar asked May 10 '10 19:05

Nick Kahn


3 Answers

Though this question is pretty old. If I was you I do something very simple like

<textarea maxlength="255"></textarea>

This would limit the users to enter only 255 characters in the textarea.

like image 62
defau1t Avatar answered Oct 31 '22 09:10

defau1t


Here's what I use to limit something to 1200 chars. When someone types too many characters, I just truncate the contents of that textarea.

$(function() {
    //set up text length counter
    $('#id_limited_textarea').keyup(function() {
        update_chars_left(1200, $('#id_limited_textarea')[0], $('#text_chars_left'));
    });
    //and fire it on doc ready, too
    update_chars_left(1200, $('#id_limited_textarea')[0], $('#text_chars_left'));

});

function update_chars_left(max_len, target_input, display_element) {
   var text_len = target_input.value.length;
   if (text_len >= max_len) {
       target_input.value = target_input.value.substring(0, max_len); // truncate
       display_element.html("0");
   } else {
       display_element.html(max_len - text_len);
   }
}
like image 28
Steve Jalim Avatar answered Oct 31 '22 07:10

Steve Jalim


$(this).val( $(this).val().substring(0, limit) );
like image 42
BlueRaja - Danny Pflughoeft Avatar answered Oct 31 '22 07:10

BlueRaja - Danny Pflughoeft