Limit the number of characters in a WYSIWYG Editor (NicEdit)

Andrea Turri picture Andrea Turri · Nov 16, 2011 · Viewed 8.3k times · Source

I have this jQuery code:

var char = 60;
    $("#counter").append("You have <strong>" + char + "</strong> char.");
    $("#StatusEntry").keyup(function () {
        if ($(this).val().length > char) {
            $(this).val($(this).val().substr(0, char));
        }
        var rest = char - $(this).val().length;
        $("#counter").html("You have <strong>" + rest + "</strong> char.");
        if (rest <= 10) {
            $("#counter").css("color", "#ff7777");
        }
        else {
            $("#counter").css("color", "#111111");
        }
    });

It works fine! But if instead a val() I have text() it doesn't work.

The problem is that at the end of available char it start to replace the text from the beginning...... using val is perfect.

Why I need it on text? Because I'm using a wysiwyg plugin and it convert my textarea to div.

I'm trying with .stopPropagation but it doesn't work.. trying with return false and nothing...

Hope in your help!

Answer

Manse picture Manse · Nov 16, 2011

If you need to use the NicEdit then you can limit the keystrokes by binding the keyup / keydown event to the newly created div (it doesnt replace your textarea - its adds a div and hides your textarea) :

$("#StatusEntry").prev().keydown(function () {

This works because the newly create div is always preceding the textarea - so this will work for multiple editors.

However as you seem to have indicated in your comments a contentEditable div may be sufficient - if it is use the following method :

    var char = 60;
    $("#counter").append("You have <strong>" + char + "</strong> char.");
    $("#StatusEntry").keyup(function () {
        if ($(this).text().length > char) {
            $(this).text($(this).text().substr(1));
        }
        var rest = char - $(this).text().length;
        $("#counter").html("You have <strong>" + rest + "</strong> char.");
        if (rest <= 10) {
            $("#counter").css("color", "#ff7777");
        }
        else {
            $("#counter").css("color", "#111111");
        }
    });

Demo : http://jsfiddle.net/RjNuX/3