user3395986
user3395986

Reputation: 25

Calling a JS function with its name and parameters in a string

I have searched for a while now, how to call javascript functions from a string (name of the function and its parameters are stored in a string). I have found much information, such like not to use eval()...

I have found solutions, but i don't get them to work. What do i do wrong?

Here is the short jsfiddle here

function insertArtikel(param1, param2, param3, param4, param5, param6) {
    alert('Called successfully');
    alert('Param1: ' + param1 + ', Param2: ' + param2 + ', Param3: ' + param3 + ', Param4: ' + param4 + ', Param5: ' + param5 + ', Param6: ' + param6);
}

$('#mybutton').on('click', function () {
    todo = $('#txt1').val();
    params = $('#txt2').val();
    alert('Now calling: '+todo+'('+params+');');
    //Maybe making an array of it:
    //params = params.replace(/'/g, '');
    //params = params.split(',');
    window[todo](params);
});

It should run the function "insertArtikel" (textfield1) and give the parameters of textfield2 when clicking the Button. SHOULD..

Thanks for all replies!

EDIT: Thanks to sabof! I not converted the string into an array correctly! Difference: False: var args = params.replace(/'/g,'').split(','); Right: var args = params.replace(/'/g,'').split(/, ?/); Now it works!!!!!! THANKS!!!

Upvotes: 0

Views: 152

Answers (1)

sabof
sabof

Reputation: 8192

The correct answer is this:

var args = params.replace(/'/g,'').split(/, ?/);
window[todo].apply(null, args);

However it won't work in JSFiddle, since JSFiddle auto-wraps the code, and insertArtikel is not a global function:

$(window).load(function(){
  function insertArtikel(param1, param2, param3, param4, param5, param6) {
    alert('Called successfully');
    alert('Param1: ' + param1 + ', Param2: ' + param2 + ', Param3: ' + param3 + ', Param4: ' + param4 + ', Param5: ' + param5 + ', Param6: ' + param6);
  }

  $('#mybutton').on('click', function () {
    todo = $('#txt1').val();
    params = $('#txt2').val();
    alert('Now calling: '+todo+'('+params+');');

    var args = params.replace(/'/g,'').split(/, ?/);
    window[todo].apply(null, args);
  });
});

Upvotes: 2

Related Questions