[javascript] How do I call a dynamically-named method in Javascript?

I am working on dynamically creating some JavaScript that will be inserted into a web page as it's being constructed.

The JavaScript will be used to populate a listbox based on the selection in another listbox. When the selection of one listbox is changed it will call a method name based on the selected value of the listbox.

For example:

Listbox1 contains:

  • Colours
  • Shapes

If Colours is selected then it will call a populate_Colours method that populates another listbox.

To clarify my question: How do I make that populate_Colours call in JavaScript?

This question is related to javascript dynamic methods

The answer is

Assuming the populate_Colours method is in the global namespace, you may use the following code, which exploits both that all object properties may be accessed as though the object were an associative array, and that all global objects are actually properties of the window host object.

var method_name = "Colours";
var method_prefix = "populate_";

// Call function:
window[method_prefix + method_name](arg1, arg2);

Similar questions with javascript tag:

Similar questions with dynamic tag:

Similar questions with methods tag: