CLEditor - Lose focus if maxlength is reached
I'm trying to recreate a maxlength - function for CLEditor. The objective is: If a text is entered into a textbox and its longer than the set maxlength, the textbox should lose its focus so that it's not possible, to write any further letters.
What I've achieved so far is that the CLEditor recognizes when the text gets longer than my maxlength. For losing the focus I've tried a simple return (i.e. return; return false;) and some .blur()-methods (i.e. $(frameDesc).blur(); and cledDesc.$area.blur();). But those are not working. I'm still able to fill in text even maxlength is reached.
Please have a look at the code:
$("#profileForm_description").cleditor({width: 430, height: 125});
var cledDesc = $("#profileForm_description").cleditor()[0];
var frameDesc = cledDesc.$frame[0].contentWindow.document;
$(frameDesc).bind('keypress change', function(){
var text = textWithoutHTML(cledDesc.$area.val());
if(text.length >= 650){
console.log("Longer than MaxLength");
开发者_如何学Go //lose focus
}else{
//Do something
}
});
Any help and hints would be appreciated :)
Solved this one. That was pretty tricky. The solution (for me) is:
Using the keydown instead of the keypress - event.
So if I'm trying to put in some text in my textbox and maxlength is reached, I'm not able to go on writing. But to be able to delete some text, I need to except the Backspace-key from being rejected too. So I've put in a check, if the pressed key is the backspace-key.
This is what the code looks like now:
$("#profileForm_description").cleditor({width: 430, height: 125});
var cledDesc = $("#profileForm_description").cleditor()[0];
var frameDesc = cledDesc.$frame[0].contentWindow.document;
$(frameDesc).bind('keydown change', function(event){
var text = textWithoutHTML(cledDesc.$area.val());
if(text.length >= 650 && event.which != 8){
console.log("Longer than MaxLength");
//lose focus / stop writing
return false;
}else{
//Do something
}
});
I've added some code to make it work.
- I catch even the "canc" key (and others)
- Before checking the length of the text I update the textarea, it looks like CLEditor has an internal cache and I had a strange behaviour after deleting and reentering text.
This is working perfectly for me:
var cledDesc = $("#oodsummary").cleditor()[0];
var frameDesc = cledDesc.$frame[0].contentWindow.document;
var limit = 10;
$(frameDesc).bind('keydown', function(event){
cledDesc.updateTextArea();
var text = cledDesc.$area.val();
if(text.length >= limit &&
event.which != 8 && // back
event.which != 46 && // canc
event.which != 37 && // left
event.which != 38 && // up
event.which != 39 && // right
event.which != 16 && // shift
event.which != 20 && // caps lock
event.which != 91 && // os special
event.which != 18 // alt
) {
alert("Il testo inserito risulta essere troppo lungo.");
cledDesc.$area.val(text.substr(0, limit)).blur();
return false;
}else{
cledDesc.updateTextArea();
return true;
}
});
精彩评论