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);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…