0

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:

http://jsfiddle.net/1m0srn3f/

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);
  • Stopping the user from entering characters is a bit unfriendly, just give them a warning and prevent submission until they've trimmed it to the required length (*a la* the comment fields here). – RobG Aug 24 '14 at 20:51

1 Answers1

0

This answer is taken from a similar question on SO and it seems to be working just as you want it.

jQuery(document).ready(function($) {
var max = 400;
$('textarea.max').keypress(function(e) {
    if (e.which < 0x20) {
        // e.which < 0x20, then it's not a printable character
        // e.which === 0 - Not a character
        return;     // Do nothing
    }
    if (this.value.length == max) {
        e.preventDefault();
    } else if (this.value.length > max) {
        // Maximum exceeded
        this.value = this.value.substring(0, max);
    }
});
}); //end if ready(fn)
Community
  • 1
  • 1
Alex
  • 4,674
  • 5
  • 38
  • 59