I am currently using a html table within my web page to allow the user to input certain details. However as there is no limit on the character input the table can be stretched largely when the user types in as many characters as they wish.
I was wondering how to limit this contenteditable to prevent this from happening?
Below is a snippet of the code I am using for the table
<tr>
<td>One Off Capital</td>
<td><div contenteditable> </div></td>
<td><div contenteditable> </div></td>
</tr>
I have found this link below to a similar problem, however being new to jQuery and an amateur developer, I am struggling to understand the answers given and how I can use them.
Limiting Number of Characters in a ContentEditable div
You can do something tricky with keypress()
event handler. Prevent keypress
event if content is greater than your limit by returning false
UPDATE : Add listener to paste
event. Then check the content length. Also prevent drag option in order to prevent content dragging to it.
var limit = 10;
$('div[contenteditable]').keypress(function() {
return this.innerHTML.length < limit;
}).on({
'paste': function(e) {
var len = this.innerHTML.length,
cp = e.originalEvent.clipboardData.getData('text');
if (len < limit)
this.innerHTML += cp.substring(0, limit - len);
return false;
},
'drop': function(e) {
e.preventDefault();
e.stopPropagation();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<tr>
<td>One Off Capital</td>
<td>
<div contenteditable></div>
</td>
<td>
<div contenteditable></div>
</td>
</tr>
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