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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With