48

Is it possible to call a function by using the strings ?

(i.e) I have a variable var target = 'next';. Using this string I want to call the jquery method next() . Should i use target + '()' (this is bit foolish) to call next() ?

I know it can be done using conditional statements. Since it is a string got from users, but it is difficult to use conditional statements for all that.

In my jQuery plugin, users will pass the value prev, siblings etc as options, so that the respective jQuery methods will be executed.

How do I implement this ?

Aakash Chakravarthy
  • 10,523
  • 18
  • 61
  • 78

3 Answers3

118

You can use the bracket notation to access the member with a string containing the identifier:

var target = 'next';
$("foobar")[target]();    // identical to $("foobar").next()
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • 2
    This is really useful if you know you can call method using `MyObject.call(myFunctionName, args);` Functional programming FTW. Thanks for the tip, Gumbo. – josemota Aug 30 '11 at 14:46
  • You should have accepted the solution of slightlymore, because this is not save. Especially because you don't know what your user types in. What if he makes a typo? The solution of slightlymore won't break your script. – Marco Sep 03 '12 at 16:54
  • @MarcoFranssen A `try … catch` could easily fix that. – Gumbo Sep 03 '12 at 19:17
  • try catching is not the way to do this. If you just check before invoking this is much better. – Marco Sep 04 '12 at 11:21
  • @MarcoFranssen In that case you should also check whether it’s actually a function, e. g. `jQuery.fn.length` is not a function. – Gumbo Sep 04 '12 at 19:04
16

If you're wanting to use jQuery, the answer is quite elegant. Because jQuery is an object (which can be accessed like an array) - you can use $("selector")[target]().

Examples:

const target = 'next';
jQuery("selector")[target]();

This will work if you know that you can trust the input. However, if you're not sure of this, you should check that the function exists before trying to run it otherwise you'll get an error.

const target = 'doesNotExist';
const fn = jQuery('selector')[target];
if (jQuery.isFunction(fn)) {
  fn[target]();
}
clinton3141
  • 4,751
  • 3
  • 33
  • 46
12

In my case I needed to get the value from a rel attribute and then parse it as a function, this worked for me.

$jq('#mainbody form').submit(function(e){
    var formcheck = $jq(this).attr('rel');
    if (typeof window[formcheck] === 'function'){
        formok = window[formcheck]();
        e.preventDefault();
    }
});
function maincheck(){
    alert("Checked");
    return false;
}

and the form

<div id="mainbody">
<form action="mainpage.php" method="post" rel="maincheck">
<input type="hidden" name="formaction" value="testpost">
<label>Field 1 <input type="text" name="field1" value="<?=$_POST['field1'];?>"></label><br>
<label>Field 2 <input type="text" name="field2" value="<?=$_POST['field2'];?>"></label><br>
<input type="submit" value="Submit Form">
</form>
</div>
Neo
  • 2,305
  • 4
  • 36
  • 70