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

久未见 提交于 2019-12-05 08:19:08

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

you have to target the nice edit div.

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

If you have multiple editors, this solution will not work.

Michael L Watson
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 function from here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!