1

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?

14
  • 1
    Which part is it telling you is null? Commented Dec 27, 2012 at 12:25
  • perhaps body has no children? Commented Dec 27, 2012 at 12:25
  • Perhaps editorInstance itself is null? Commented Dec 27, 2012 at 12:26
  • sorry.. I'll edit the question Commented Dec 27, 2012 at 12:26
  • 1
    You still haven't shown us the error message. Commented Dec 27, 2012 at 12:32

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0
 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 ;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.