I have a few areas on my site where I need to limit text input to X amount of characters and it\'s nice to show a number of spaces left while a user types in, like twitter d
So I took @deceze version and added a bit of trick to make it:
add class - to color the text - when it is over the limit (extra css is needed for this of course)
$(document).ready(function(){
var left = 200
$('#field_counter').text('Characters left: ' + left);
$('#id_description').keyup(function () {
left = 200 - $(this).val().length;
if(left < 0){
$('#field_counter').addClass("overlimit");
}
if(left >= 0){
$('#field_counter span').removeClass("overlimit");
}
$('#field_counter').text('Characters left: ' + left);
});
});
For anyone needing the same as me :)
Using jQuery, assuming that you have a textarea with id field that you wish to limit to 100 characters, and another element with id chars-remaining to display the number of available characters:
var max = 100;
$('#field').keyup(function() {
if($(this).val().length > max) {
$(this).val($(this).val().substr(0, max));
}
$('#chars-remaining').html((max - $(this).val().length) + ' characters remaining');
});
Keep in mind that you have to account for NewLines being 2 characters.
I built upon the solutions provided here to the below code which accounts for new lines.
function DisplayCharactersLeft(idOfInputControl) {
var maxNumberOfCharacters = $("#" + idOfInputControl).attr("maxLength");
$("#" + idOfInputControl).on("input", function () {
var currentText = $(this).val();
var numberOfNewLines = GetNumberOfNewLines(currentText);
var left = maxNumberOfCharacters - (currentText.length + numberOfNewLines);
if (left < 0) { left = 0; }
$("#" + idOfInputControl + "CharactersLeftCounter").text("Characters left: " + left);
});
}
function GetNumberOfNewLines(text) {
var newLines = text.match(/(\r\n|\n|\r)/g);
var numberOfNewLines = 0;
if (newLines != null) {
numberOfNewLines = newLines.length;
}
return numberOfNewLines;
}