I am working on an jQuery function that allows to count chars and linebreaks in an textarea. So far, counting the chars works, but I haven't yet managed to achieve that the user CANNOT type on once the set chars limit has been reached.
Here comes my fiddle:
HTML:
<textarea id="exampleArea"></textarea>
<p id="left_chars">200</p>
JS:
(function($) {
$.fn.extend({
limiter : function(limit, charsBox, subtractionOnEnter) {
$(this).on("keyup focus", function(e) {
setCount(this, charsBox, subtractionOnEnter, e);
});
$(this).on("focus", function() {
setCount(this, charsBox, subtractionOnEnter);
});
function setCount(src, charsBox, subtractionOnEnter, e) {
// get number of current chars in text
var chars = src.value.length;
// Process linebreaks
if (subtractionOnEnter !== undefined) {
// Look for linebreaks ("\n" occurences)
var matches = src.value.match(/\n/g);
// count them, if there are any
var linebreaks = matches ? matches.length : 0;
console.log('number of linebreaks: '+linebreaks);
// substract linebreak chars equivalents from chars
chars += (linebreaks * subtractionOnEnter);
}
console.log('final chars: '+chars);
// Update indication of remaining chars
charsBox.html(limit - chars);
}
setCount($(this)[0], charsBox);
}
});
})(jQuery);
$('#exampleArea').limiter(200, $('#left_chars'), 50);