Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...