Ifedi Okonkwo
Ifedi Okonkwo

Reputation: 3656

How do I call a jQuery function with a dynamic name?

I can't believe that I've been unable to dig out a solution to this problem. It looked to me like a very "regular" problem whose solution would litter the web!

I have these arrays returned from a database query:

var ids = ['12', '15', '40'];
var actions = ['hide', 'show', 'fadeIn'];

I want to loop through the arrays and carry out the appropriate action on the DOM, like so:

for(var i=0; i < ids.length; i++){
    $('#row_'+ids[i]).actions[i]();
}

Now you get the idea. Actually I didn't expect the $('#row_'+ids[i]).actions[i](); to work as is. I have tried things like

$('#row_'+ids[i]).effect(actions[i]);

To no avail. I believe eval() should work and (in desperation) even tried that but couldn't get the right string for it to work.

Elsewhere on Stack Overflow, I have come across similar issues solved using the window global, like:

var fn = 'hideSomething';
window.fn();//where hideSomething was a defined function.

But this one is defined on jQuery, not on window.

So here we are!

Upvotes: 3

Views: 1761

Answers (2)

Josh Crozier
Josh Crozier

Reputation: 241078

Use square bracket notation in order to access the property:

for (var i = 0; i < ids.length; i++) {
  $('#row_' + ids[i])[actions[i]]();
}

Example Here

See: Property accessors in JS (MDN)

Upvotes: 2

jfriend00
jfriend00

Reputation: 707706

You need to use [varhere] to access a property/method by variable name. Since your property name is in actions[i], then you would do this:

$('#row_'+ids[i])[actions[i]]();

Or, in a slightly easier scheme to follow exactly what is happening:

var method = actions[i];
$('#row_'+ids[i])[method]();

You can use the dot syntax obj.prop when the property name is known ahead of time. When it's in a variable and not known ahead of time, you use the obj[prop] syntax. Since a method is just a property, the same applies to jQuery methods too.

for(var i=0; i < ids.length; i++){
    $('#row_'+ids[i])[actions[i]]();
}

Upvotes: 5

Related Questions