Setting max length in summernote
Asked Answered
Z

5

7

How can I apply a maxlength to Summernote? Applying a maxlength to the textarea does not work here.

https://github.com/summernote/summernote

$("#textareaid").summernote({
      toolbar:[
        ['style', ['style']],
        ['font', ['bold', 'italic', 'underline', 'superscript', 'subscript', 'strikethrough', 'clear']],
        ['fontname', ['fontname']],     
        ['fontsize', ['fontsize']], 
        ['color', ['color']],
        ['para', ['ul', 'ol', 'paragraph']],
        ['height', ['height']],
        ['table', ['table']],
        ['insert', ['link', 'picture', 'video', 'hr']],
        ['view', ['fullscreen', 'codeview']],
        ['help', ['help']]      
      ],                  
      height: 250,  
      focus: true 
});

$("#summernotediv").code("");           
$('.note-help-dialog .row-fluid >p').hide();    
$('.note-editable').css('overflow','auto'); 
$('.note-image-input').prev('h5').remove();
$('.note-image-input').remove();
Zomba answered 17/12, 2014 at 14:36 Comment(0)
C
32

you can make it with callback object and preventDefault function.

This sample is with 400 limit.

  function registerSummernote(element, placeholder, max, callbackMax) {
    $(element).summernote({
      toolbar: [
        ['style', ['bold', 'italic', 'underline', 'clear']]
      ],
      placeholder,
      callbacks: {
        onKeydown: function(e) {
          var t = e.currentTarget.innerText;
          if (t.length >= max) {
            //delete key
            if (e.keyCode != 8)
              e.preventDefault();
            // add other keys ...
          }
        },
        onKeyup: function(e) {
          var t = e.currentTarget.innerText;
          if (typeof callbackMax == 'function') {
            callbackMax(max - t.length);
          }
        },
        onPaste: function(e) {
          var t = e.currentTarget.innerText;
          var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');
          e.preventDefault();
          var all = t + bufferText;
          document.execCommand('insertText', false, all.trim().substring(0, 400));
          if (typeof callbackMax == 'function') {
            callbackMax(max - t.length);
          }
        }
      }
    });
  }


$(function(){
  registerSummernote('.summernote', 'Leave a comment', 400, function(max) {
    $('#maxContentPost').text(max)
  });
});
    
<!-- include libraries(jQuery, bootstrap) -->
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>

<!-- include summernote css/js -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.9/summernote.js"></script>

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <div class="summernote"></div>
    </div>
    <div class="col-xs-12 text-right">
      <span id="maxContentPost"></span>
    </div>
  </div>
</div>
Carpi answered 18/7, 2016 at 20:9 Comment(2)
Great! How would you do that for a limit in words? Since it seems to be more useful for a non-informatic end-user (for example, those from the social sciences) to know the limit in terms of number of words, and not in characters ...Chubb
Hi @Pathros, good question and it could be an interesting topic. But I don't think that should be solved under this thread. I mean the algorithm to solve your question doesn't affect to the current question. Could you open a new question for that? Even other persons could participate :)Carpi
S
8

Based on Angel Fraga Parodi's answer I added some more keyCodes that should always be allowed like delete, arrow keys or ctrl+x/ctrl+c. Also the code for pasting wasn't working (anymore). Here's an updated version:

<div class="summernote" ></div>
<h5 id="maxContentPost" style="text-align:right"></h5>
<script>
        $(document).ready(function () {
            $('.summernote').summernote({
                toolbar: [
                  ['style', ['bold', 'italic', 'underline', 'clear']]
                ],
                placeholder: 'Leave a comment ...',
                callbacks: {
                    onKeydown: function (e) { 
                        var t = e.currentTarget.innerText; 
                        if (t.trim().length >= 400) {
                            //delete keys, arrow keys, copy, cut, select all
                            if (e.keyCode != 8 && !(e.keyCode >=37 && e.keyCode <=40) && e.keyCode != 46 && !(e.keyCode == 88 && e.ctrlKey) && !(e.keyCode == 67 && e.ctrlKey) && !(e.keyCode == 65 && e.ctrlKey))
                            e.preventDefault(); 
                        } 
                    },
                    onKeyup: function (e) {
                        var t = e.currentTarget.innerText;
                        $('#maxContentPost').text(400 - t.trim().length);
                    },
                    onPaste: function (e) {
                        var t = e.currentTarget.innerText;
                        var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');
                        e.preventDefault();
                        var maxPaste = bufferText.length;
                        if(t.length + bufferText.length > 400){
                            maxPaste = 400 - t.length;
                        }
                        if(maxPaste > 0){
                            document.execCommand('insertText', false, bufferText.substring(0, maxPaste));
                        }
                        $('#maxContentPost').text(400 - t.length);
                    }
                }
            });
        });
</script>
Schouten answered 24/1, 2018 at 15:3 Comment(1)
Very nice... I also noticed some commands problem. In yours it is missing select all (ctrl + a ). I have added it. !(e.keyCode == 65 && e.ctrlKey)Staphyloplasty
T
0

use the 'onKeydown' callback to check the current length of the editor's contents and possibly prevent further typing if that value is greater than or equal to the max length of your choice.

onKeydown: function(e) {
            if (e.keyCode == 8 /*and other buttons that should work even if MAX_LENGTH is reached*/) 
                return;
            if ($(".note-editable").text().length >= MAX_LENGTH){
                e.preventDefault();
                return;
            }    
},
Trimetallic answered 27/11, 2016 at 15:3 Comment(0)
I
0

I wrote this jquery solution based on the Summernote .note-editable class.

//Contador de Caracteres para summernote
$(".note-editable").on("keypress", function(){
    var limiteCaracteres = 255;
    var caracteres = $(this).text();
    var totalCaracteres = caracteres.length;

    //Update value
    $("#total-caracteres").text(totalCaracteres);

    //Check and Limit Charaters
    if(totalCaracteres >= limiteCaracteres){
        return false;
    }
});

To display character count, just add a <span id="total-caracteres"></span> after <div class="summernote"></div>.

Insular answered 25/8, 2017 at 23:59 Comment(0)
M
0

After researching this for a bit, I stumbled upon a poorly documented "maxTextLength" option.

You can see it in the code here.

It works well for my use case, but the only caveat is users won't be able to paste anything in at all if it's greater than your character limit. Ideally the pasted text would be cut off at the character limit, so it looks like a bug to the end user.

Median answered 12/6 at 21:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.