1

Possible Duplicate:
Use javascript variable in object name

I am using CKeditor as a rich text editor. I have dynamically generated textareas with a unique ID that need replacing with text editors. That is working fine, but I then need to call getData(); on the textarea to get the data for an AJAX call. This is easy enough:

var editor_data = CKEDITOR.instances.editor1.getData();

The problem is I need editor1 to be dynamic, depending on the value of an attribute on a button. I record the textarea's identifier in a sibling button's name attribute:

var INSTANCE_NAME = $(this).attr('name');

Logging that out I get the correct editor ID back. (Note only using CAPS to highlight where it needs to be used in the next code block.)

I now need to use that INSTANCE_NAME as a variable like so:

var editor_data = CKEDITOR.instances.INSTANCE_NAME.getData();

I imagine my entire code needs to look something like this:

var INSTANCE_NAME = $(this).attr('name');
var editor_data = CKEDITOR.instances.INSTANCE_NAME.getData();

But I just get an error that CKEDITOR.instances.INSTANCE_NAME is undefined (which isn't surprising really)

Thanks

0

2 Answers 2

2

There are two ways to access properties in an object:

  1. object.property
  2. object['property']

Because the second option takes the property name as a string, you can build it dynamically — in this case, using the string INSTANCE_NAME:

var INSTANCE_NAME = $(this).attr('name');
var editor_data = CKEDITOR.instances[INSTANCE_NAME].getData();
//                                  \_____________/
//                                         ^
Sign up to request clarification or add additional context in comments.

Comments

1

Use square brackets:

var editor_data = CKEDITOR.instances[INSTANCE_NAME].getData();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.