21

I would like to limit number of chars in my editable div to 10. After user reach the limit I would like to use .preventDefault() method to protect the div from additional chars. Can you help me out, please?

JSFiddle https://jsfiddle.net/7x2dfgx6/1/

HTML

<div class="profileInfo" id="About" style="border:solid;" contenteditable="true">OOOOO</div>

JQuery

    jQuery(document).ready(function($){

    const limit = 10;
    rem = limit - $('#About').text().length;
    $("#counter").append("You have <strong>" + rem + "</strong> chars left.");
    $("#About").on('input', function(event) {
        var char = $('#About').text().length;
        rem = limit - char;
        $("#counter").html("You have <strong>" + rem + "</strong> chars left.");
        if(char>limit)
        {
            event.preventDefault();
            //TODO
        }
    });
});
Da Artagnan
  • 1,109
  • 3
  • 17
  • 26

7 Answers7

28

To answer your main question:
.preventDefault() cancel behavior of the events that are cancelable. input event is not .

To check whether an event is cancelable, try: console.log(event.cancelable);.
For input it will say "false"


You may want something like this (untested):

const limit = 10;
var rem = limit - $('#About').text().length;
$("#counter").append("You have <strong>" + rem + "</strong> chars left.");
$("#About").on('input', function(event) {
    var char = $(this).text().length;
    rem = limit - char;
    if(rem <= 0){
        $(this).text($(this).text().slice(0, limit));
    }
    $("#counter").html("You have <strong>" + rem + "</strong> chars left.");
});

EDIT

JSFiddle demo
Since it's contentEditable, I had to use an additional code (from this answer) to set a caret at the end of the input.

OzgurG
  • 1,634
  • 1
  • 16
  • 21
Artur Filipiak
  • 9,027
  • 4
  • 30
  • 56
  • Hi do you know how to set the caret to the end (using this code) when trying to target an iframe > body element? The body element has `editablecontent="true"` and `placeCaretAtEnd(this);` won't work for me. Also see: https://stackoverflow.com/q/51400927/5660293. Thanks a million! – RobbTe Jul 18 '18 at 19:46
  • @Bernat This surely fails if a person fails to understand the principles of "an example". Also - assuming that you read the question carefully - could you elaborate on what exactly is the advantage of the `maxlength` attribute in the OP context? – Artur Filipiak Feb 11 '23 at 17:16
9

use keydown instead of input

jQuery(document).ready(function($){

    const limit = 10;
    rem = limit - $('#About').text().length;
    $("#counter").append("You have <strong>" + rem + "</strong> chars left.");
    $("#About").on('keypress', function(event) {
        var char = $('#About').text().length;
        if(char>limit)
        {
            return false;
            //or
            event.preventDefault();
            //TODO
        }
        rem = limit - char;
        $("#counter").html("You have <strong>" + rem + "</strong> chars left.");

    });

});

DEMO

1
el.addEventListener('input', function(event) {

 if ( this.innerHTML.length >300  && event.keyCode != 8) {

   document.execCommand("undo");  

 }

 });
PN GH
  • 25
  • 1
  • 1
    Would you please explain the code and how to apply it as concisely as possible? – Wolfpack'08 Feb 27 '20 at 11:30
  • 300- max lenth ; event.keyCode != 8 - delete; document.execCommand("undo"); - cancel last action("input") – PN GH Feb 28 '20 at 19:40
  • 1
    document.execCommand is marked as deprecated, see MDN documentation (https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand) - this is NOT reliable solution for production site. – Xerix Apr 20 '21 at 06:46
0

Here is one way to limit the characters in an input. Works with paste and typing.

/**
 * Limit an inputs number of characters
 * @param {event} e - event of the input the user is typing into
 * @param {number} limit - number of characters to limit to 
 */
function limitInputCharacters(e, limit){
  if(!e){
    return;
  }
  var inputText = e.target.value;
  var charsLeft = limit - inputText.length;
  if (charsLeft >= 0) {
    // do something, or nothing
  } else if (charsLeft < 0) {
    e.target.value = inputText.slice(0, limit)
  }
}

document.addEventListener("DOMContentLoaded", function() {
  const aboutTextArea = document.getElementById('input-about');
  aboutTextArea.addEventListener("input", function(e) {
    limitInputCharacters(e, 300)
  })
})
moto
  • 946
  • 10
  • 27
0

I tried this solution with JavaScript.

Also below the input is the character counter.

HTML:

<input type="text" class="about">
<span></span>

javascript:

let about = document.querySelector("input")
    let text = document.querySelector("span")
    const limit = 10
   about.addEventListener("keypress" ,function(event) {

    let char = about.value.length;
    if(char>=limit){
        event.preventDefault();
    }
    let rem = limit - char

    text.innerText = ` You have ${rem} chars left.`

})
0

Use the beforeinput¹ event without jQuery²

  • ¹ The beforeinput event wasn't available when the question was asked.
  • ² jQuery does not pass InputEvent to the listener callback.
document.getElementById("myinput").addEventListener('beforeinput', function(event) {
    if (event.inputType.startsWith("insert")) {
        const totalLength = this.innerText.length + event.data.length;
        if (totalLength > 10)
            event.preventDefault()
    }
});

See more in the MDN page for the beforeinput event.

psqli
  • 588
  • 6
  • 11
-1

Try changing the value of the contenEditable attribute. Also I set the check for the limit to >=

jQuery(document).ready(function($){

    const limit = 10;
    rem = limit - $('#About').text().length;
    $("#counter").append("You have <strong>" + rem + "</strong> chars left.");
    $("#About").on('input', function(event) {
        var char = $('#About').text().length;
        rem = limit - char;
        event.preventDefault();
        if(char>=limit)
        {
            $('#About').attr('contenteditable','False');
            //TODO
        }
        $("#counter").html("You have <strong>" + rem + "</strong> chars left.");
    });

});
grantk
  • 3,958
  • 4
  • 28
  • 37
  • By trying to prevent the default you would be only stopping the input event from firing, not actually stopping the user from being able to input more data. – grantk Aug 30 '15 at 15:28
  • After users reach the limit I would like to enable them to use backspace. You see for example user wanted to write down long word and he misscalculate the word lenght, he should be able to erase, by using backspace, the whole word and write down another. – Da Artagnan Aug 30 '15 at 15:34