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(f
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);
}
}
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.
$(this).val( $(this).val().substring(0, limit) );
var limit="NO of characters";<br><br>
$(this).val( $(this).val().substring(0, limit) );
To simplify this to the bare bone basic:
<textarea name="message" onkeydown="return this.value.substr(0,160)"></textarea>
Set your max to where 160 is.
My plugin:
(function($) {
$.fn.textCounter = function(options) {
var defaults = {
maxlimit: 100, // max limit character
description: null, // element for descript count character
enter: true // if accept enter
};
var options = $.extend({}, defaults, options);
if (options.description != null) {
if (typeof options.description == 'string')
options.description = $('#' + options.description);
}
var fevent = function(ev) {
var value = $(this).val(),
k = ev.charCode || ev.keyCode || ev.which,
incremente = 1;
if (k == 8)
incremente = -1;
if (options.enter == false && k == 13)
return false;
if (ev.ctrlKey || ev.altKey || ev.metaKey) //Ignore
return true;
if ((value.length + incremente) > options.maxlimit)
return false;
return true;
};
var fcounter = function(ev) {
var value = $(this).val();
$(options.description).text(options.maxlimit - value.length);
};
$(this).each(function(i, el) {
if ($(this).is(':input')) {
$(this).unbind('keypress.textCounter').bind('keypress.textCounter', fevent);
$(this).unbind('keyup.textCounter').bind('keyup.textCounter', fcounter);
}
});
};
})(jQuery);