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

Community
  • 1
  • 1
kieran
  • 2,304
  • 4
  • 28
  • 44

2 Answers2

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();
//                                  \_____________/
//                                         ^
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

Use square brackets:

var editor_data = CKEDITOR.instances[INSTANCE_NAME].getData();
James Allardice
  • 164,175
  • 21
  • 332
  • 312