1

We want to concatenate the function name and variable name. This should occur on click of a <a> tag.

How can we concatenate the function and variable name?

Issue:

  • we are getting error message fn_dataId() is not defined

Desired output:

fn_dataId() should be fn_some123();

What we tried

$(function() {
    $('.link').on('click', function() {
      console.log('clicked');
      var dataId = $(this).attr('data-id');
      console.log('data id - ' + dataId);
      
      // What we tried, but didn't work. 
      fn_dataId(); 
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-id="some123" class="link">
Click here
</a>
usernameabc
  • 662
  • 1
  • 10
  • 30

2 Answers2

5

You can concatenate strings, and use the result as a function using window["function_name"](args);:

function fn_some123() {
  console.log('i have been called!');
}

$(function() {
    $('.link').on('click', function() {
      var dataId = $(this).attr('data-id');
      window['fn_' + dataId]();
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a data-id="some123" class="link">
Click here
</a>
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
-2

I'm not sure the use case of this it sounds like the dataId might be better off as an argument to a more generic function, but you can possibly solve it using the following:

eval("fn_" + dataId + "()")

Be wary of eval though - executing anything you take as input from a user is a big security risk

I_Adze
  • 89
  • 1
  • 7
  • `eval` is something you should forget even exists. You know, you hit a bus and than you learn to avoid the bus... and you walk... and you're happy... – Roko C. Buljan Aug 29 '19 at 22:48