2

I have a jQuery function wherein I count the characters left on keyup.

function charactersLeft(e) {
    var textArea = e.data.textArea,
            charLeft = e.data.maxLength - textArea.val().length,
            message = e.data.messageContainer;

    if (charLeft < e.data.warningLength) {
        message.addClass('red').removeClass('green');
    }
    else {
        message.addClass('green').removeClass('red');
    }

    message.text(charLeft);
}

This one works fine but it counts the carriage return as one character instead of two. This causes a problem when it's passed to the server since the carriage return is passed as '\r\n'.

What can I do to modify my code so that whenever I hit enter, the character count subtracts 2 instead of 1 and adds 2 instead of 1 when a carriage return is deleted?

Thank you :)

4

2 回答 2

0

keyup 的 if 条件?

把类似的东西if(e.which==13){charLeft--}。这将减去一个额外的计数。

于 2013-01-21T08:14:19.630 回答
0

下面是您正在寻找的代码。

下面的代码也经过测试。

<script type="text/javascript" src="js/jquery.js"></script>

<script type="text/javascript">

(function($)
{ 
    $.fn.extend(
    {
        limit: function(limit,element)
        {
            var interval, f;
            var self = $(this);

            $(this).focus(function()
            {
                interval = window.setInterval(substring,100);
            });

            $(this).blur(function()
            {
                clearInterval(interval);
                substring();
            });

            substringFunction = "function substring(){ var val = $(self).val();var length = val.length;if(length > limit){$(self).val($(self).val().substring(0,limit));}";
            if(typeof element != 'undefined')
                substringFunction += "if($(element).html() != limit-length){$(element).html((limit-length<=0)?'0':limit-length);}"

            substringFunction += "}";

            eval(substringFunction);
            substring();
        } 
    }); 
})(jQuery);

</script>

<textarea id="myTextarea"></textarea>
<script type="text/javascript">
    $(document).ready(function()
    {
        $('#myTextarea').limit('140','#charsLeft');
    });    
</script>
<div id="charsLeft"></div>
于 2013-01-21T08:17:04.603 回答