Question

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

Was it helpful?

Solution

an if condition on keyup?

Putting something like if(e.which==13){charLeft--}. This will substract one extra count.

OTHER TIPS

below is the code you are looking for.

below code is also tested.

<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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top