计算文本区域中的字符和换行符

Counting chars and linebreaks in textarea

本文关键字:字符 换行符 文本 区域 计算      更新时间:2023-09-26

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

我的小提琴来了:

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

这个答案来自于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)