Limit the number of characters in the WYSIWYG editor (NicEdit)

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");
        }
    });

All perfectly! But if instead of val () I have text (), it does not work.

The problem is that at the end of the available char, it starts replacing the text from the very beginning ...... using val perfectly.

Why do I need this in the text? Because I use the wysiwyg plugin and convert my text box to div.

I am trying with .stopPropagation, but this does not work .. trying to return false and nothing ...

I hope for your help!

+5
source share
3 answers

NicEdit, , keyup/keydown div ( - div ):

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

, div - .

, , , , contentEditable div - :

    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");
        }
    });

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

+7

div.

$(".nicEdit-main").keyup(...

, .

0
var len = 40;    
$(".nicEdit-main").keydown(function () {
    if($(".nicEdit-main").html().length>len){
        var string = $('.nicEdit-main').html();
        $('.nicEdit-main').html(string.substring(0, len));
        placeCaretAtEnd($('.nicEdit-main').get(0));
    }
});

placeCaretAtEnd

0

All Articles