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?
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.
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);
}
}
$(this).val( $(this).val().substring(0, limit) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With