0

I want to call a function depending upon the data-value value of the <a> that is clicked. Is this possible? I tried [call](); and call();. Both return errors.

function a() {
  alert("Hi");
}

function b() {
  alert("Bye");
}

$(function() {
  $("a").click(function() {
    var call = $(this).attr('data-value');
   [call]();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-value="a">A</a>
<a data-value="b">B</a>
Brett Malone
  • 111
  • 1
  • 1
  • 8
  • I think this questions answer will help you https://stackoverflow.com/questions/969743/how-do-i-call-a-dynamically-named-method-in-javascript – FroboZ Apr 24 '20 at 19:33
  • Does this answer your question? [How to call a function using a dynamic name in JS](https://stackoverflow.com/questions/43726544/how-to-call-a-function-using-a-dynamic-name-in-js) – Armando K. Apr 24 '20 at 19:33

2 Answers2

2

You can call it from the window object.

The window object in HTML 5 references the current window and all items contained in it. Hence we can use it to run a function in a string along with parameters to the function.

$(function(){
    $("a").click(function() {  
        var call = $(this).attr('data-value')
        window[call]();
    }); 
});

You can do it by using eval() too. But note, the eval() method is older and it is deprecated.

$(function(){
    $("a").click(function() {  
        var call = $(this).attr('data-value')
        eval(call)();
    }); 
});
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30
0

You should use the eval function, which evaluates code represented as a string, e.g.:

function a() {
  alert("Hi");
}

function b() {
  alert("Bye");
}

$(function() {
  $("a").click(function() {
    eval($(this).attr('data-value') + '()');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-value="a">A</a>
<a data-value="b">B</a>
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
  • This approach has a long list of problems and should not be used, as there are better ways of doing it. – Pointy Apr 24 '20 at 19:42