Reputation: 1469
I have a textarea where I use javascript to check if there's something writen on it:
if (!editorInstance.document.getBody().getChild(0).getText()) {
do some action
}
It works fine for firefox, but in IE9 I get this error telling it's a null or undefined object (so IE doesnt check my condition). so I tried:
var hasText = editorInstance.document.getBody().getChild(0).getText();
if (typeof hasText === 'undefined') {
do some action
}
The problem is that it still stops in the first line ( var hasText = edit...
), because the editorInstance.document.getBody().getChild(0).getText()
returns null or undefined
EDIT
when I do editorInstance.document.getBody().getChild(0).getText()
, I get all text entered in the textarea, but when there's no text entered (I check it to validate this field), this code returns nothing, this is why the hasText
variable is not working the way I expected.
Any idea about how can I solve it?
Upvotes: 1
Views: 2874
Reputation: 1
function test() {
var editor_val1 = CKEDITOR.instances.id1.document.getBody().getChild(0).getText() ;
var editor_val2 = CKEDITOR.instances.id2.document.getBody().getChild(0).getText() ;
var editor_val3 = CKEDITOR.instances.id3.document.getBody().getChild(0).getText() ;
if ((editor_val1 == '') || (editor_val2 == '') || (editor_val3 == '')) {
alert('Editor value cannot be empty!') ;
return false ;
}
return true ;
}
Upvotes: 0
Reputation: 13622
You need to check for the presence of each variable and function result that you refer to.
var firstChild = editorInstance && editorInstance.document && editorInstance.document.getBody() && editorInstance.document.getBody().getChild(0);
if (!firstChild || firstChild.getText() === '') {
// do some action
}
&&
is Javascript's logical AND operator. It’s very handy for cases like this, when you want to fetch an object's value, but the object itself might be null or undefined.
Consider the following statement:
var doc = editorInstance && editorInstance.document;
It means the same as
var doc;
if (editorInstance) {
doc = editorInstance.document;
} else {
doc = editorInstance;
}
but it's shorter. This statement will not error out if editorInstance
is null.
Upvotes: 1