计算textarea中的字符和换行符

时间:2014-08-24 20:02:30

标签: javascript jquery

我正在开发一个jQuery函数,它允许计算textarea中的字符和换行符。到目前为止,计算字符是有效的,但是我还没有设法实现用户在达到设置字符限制后无法输入。

这是我的小提琴:

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);

1 个答案:

答案 0 :(得分:0)

这个答案取自similar question on SO,它似乎正如您所愿。

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)