Search code examples
jquerytextareacarriage-returncharactercount

jQuery textarea character count (including carriage return)


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


Solution

  • an if condition on keyup?

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