Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  43] [ 4]  / answers: 1 / hits: 68251  / 14 Years ago, wed, may 19, 2010, 12:00:00

I am using contenteditable div elements in my web application and I am trying to come up with a solution to limit the amount of characters allowed in the area, and once the limit is hit, attempting to enter characters simply does nothing.


This is what I have so far:


var content_id = 'editable_div';

// Binding keyup/down events on the contenteditable div
$('#' + content_id).keyup(function(){ check_charcount(content_id, max); });
$('#' + content_id).keydown(function(){ check_charcount(content_id, max); });

function check_charcount(content_id, max)
{
if($('#' + content_id).text().length > max)
{
$('#' + content_id).text($('#' + content_id).text().substring(0, max));
}
}

This does limit the number of characters to the number specified by 'max', however once the area's text is set by the jQuery .text() function the cursor resets itself to the beginning of the area.


So if the user keeps on typing, the newly entered characters will be inserted at the beginning of the text and the last character of the text will be removed. So really, I just need some way to keep the cursor at the end of the contenteditable area's text.


More From » jquery

 Answers
25

Pass the event object to your function and call e.preventDefault() if the maximum is reached:


var content_id = 'editable_div';

max = 10;

//binding keyup/down events on the contenteditable div
$('#'+content_id).keyup(function(e){ check_charcount(content_id, max, e); });
$('#'+content_id).keydown(function(e){ check_charcount(content_id, max, e); });

function check_charcount(content_id, max, e)
{
if(e.which != 8 && $('#'+content_id).text().length > max)
{
// $('#'+content_id).text($('#'+content_id).text().substring(0, max));
e.preventDefault();
}
}

Although, you may need to do a little more to allow the user to do things like 'delete'.


Also, you could probably get rid of the keyup handler. keydown should be enough.


[#96735] Monday, May 17, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dorab

Total Points: 22
Total Questions: 106
Total Answers: 99

Location: El Salvador
Member since Fri, May 8, 2020
4 Years ago
;