Content editable Character count issue

380 views Asked by At

I have a content editable div and I wrote a custom function to get the character count which is as below:

var charCount = function (elem, event)  {
    var charBox = elem.find('.maxLengthCount'),
        txtBox = elem.find('textarea'),
        rte = elem.find('.textareaEditBox'),
        maxLength = parseInt(txtBox.attr('maxLength'));

    if(!rte.hasClass('placeholderText'))    {
        /* This is where the remaining characters are being counted */

        var remainingChars =  maxLength - rte.prop('innerHTML').length;

        charBox.html(remainingChars);
        if (remainingChars < 0) {
            charBox.parent('div').addClass('fntRed');
            rte.addClass('borderRed');
            txtBox.addClass('error');
        } else {
            charBox.parent('div').removeClass('fntRed');
            rte.removeClass('borderRed');
            txtBox.removeClass('error');
        }
    } else {
        charBox.html(maxLength);
    }           
}

charCount(wrapper, null);

editor.on('keyup', function(event)  {
    charCount($(this).closest('.field-wrapper'), event);
});

ISSUE: Everytime I press < or > the char count reduces by 4, everytime I press space bar the char count reduces by 6

2

There are 2 answers

0
micnic On

When you are editing the content of the contenteditable elements some characters get transformed in their html escapes:

"<" -> &#60; or &lt; (lesser than)
">" -> &#62; or &gt; (greater than)
" " -> &nbsp;        (Non-breaking space)

You will have to replace these characters with their original value to count correctly the number of characters in the text. Why don't you use a textarea for this purpose? With contenteditable elements you will get in more troubles like pasting images or links, textareas are just for texts and do not escape the characters like in your case.

1
RoToRa On

Count the characters of the text (or value assuming it's a textarea element), not the HTML in the element:

var remainingChars =  maxLength - rte.val().length;