Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set max length for content editable element

I have got this code

<div id="IIYBAGWNBC" contenteditable="true"></div>

And this in jquery

$("#IIYBAGWNBC").text(function(index, currentText) {
  return currentText.substr(0, 100);
});

How do I prevent the user to enter more than 100 characters in contenteditable div

like image 431
J.doe Avatar asked Nov 05 '15 17:11

J.doe


People also ask

How do I limit words in HTML?

The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.

How do I make HTML content editable?

Answer: Use the HTML5 contenteditable Attribute You can set the HTML5 contenteditable attribute with the value true (i.e. contentEditable="true" ) to make an element editable in HTML, such as <div> or <p> element.

What is Contenteditable?

The contenteditable global attribute is an enumerated attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing.

How do I make content editable in Javascript?

You can add the contenteditable="true" HTML attribute to the element (a <div> for example) that you want to be editable. If you're anticipating a user to only update a word or two within a paragraph, then you could make a <p> itself editable.


1 Answers

It's pretty simple, on keydown, count the length of element's string and prevent user if he tries to feed more than 100 chars

$('div').on('keydown paste', function(event) { //Prevent on paste as well

  //Just for info, you can remove this line
  $('span').text('Total chars:' + $(this).text().length); 

  //You can add delete key event code as well over here for windows users.
  if($(this).text().length === 100 && event.keyCode != 8) { 
    event.preventDefault();
  }
});

Demo

Explanation:

On keydown or paste event on the contenteditable div we check if the length of the div reached 100 and if user is not clicking backspace key than prevent user to feed in more characters by clicking any key or even pasting with right click.

like image 104
Mr. Alien Avatar answered Sep 19 '22 15:09

Mr. Alien