venkat
venkat

Reputation: 17

Not to allow more than 1 character in contenteditable div

currently I am working on a page which is having cross-word puzzle. Hence, I am in the situation to stop typing more than one character in content editable div. Please note that this is for epub development. Hence, I can't use input tag. Please guide me in this regards.

I tried following script in div itself. But it is not allowing me to type any character after I used backspace.

onkeypress="return (this.innerText.length >= 1 ? false : true )"

Since, I have due to the client in another one day. It will be great, if you solved this issue.

Thanks in advance...

Upvotes: 0

Views: 611

Answers (2)

Shaunak D
Shaunak D

Reputation: 20626

Demo Fiddle

Use a callback to keypress. (Works for backspace, delete)

$('div').on('keypress',function(){
     return ($(this).text().length<1)
});

Also you might need to handle copy-paste

$('div').on('paste',function(e){
    e.preventDefault();
});

Demo with paste handled

Upvotes: 1

King King
King King

Reputation: 63317

To allow other control keys, you should handle the onkeydown event instead, but note that at the time onkeydown is triggered, the typed key has not been appended to the text field. So instead of checking for text length being 1, we'll check for it being 0.

$('div').keydown(function(e){
   return $.inArray(e.which, [8, 46, 37, 39]) > -1 || $(this).text().length == 0;
});

8 is keycode for Backspace, 46 is key code for Delete, 37 and 39 are keycodes for Left arrow and Right arrow respectively.

Demo.

A sub note about using return false; to cancel the event, normally we should use e.preventDefault() because return false; also means e.stopPropagation() is called.

Upvotes: 1

Related Questions