1

I am trying to create JavaScript function dynamically and want to use input value as function name.

I tried:

function calculate(){
var dur = document.getElementById('duration').value; //example value: 1
var sum = document.getElementById('sum_insured2').value; //example value: 1000  
`'show_d'+dur+'_sum'+sum();`
}

I want like this:

`show_d1_sum1000();`

I am not getting the output what I want.

2 Answers2

2

You cannot dynamically call a function based on the value of variables in the manner you're attempting.

One workaround would be to put the function in an object and then use bracket notation to invoke the property, something like this:

var funcs = {
  'show_d1_sum1000': function() { // 1 | 1000
    console.log('foo bar');
  }
}

var dur = document.getElementById('duration').value;
var sum = document.getElementById('sum_insured2').value;

funcs[`show_d${dur}_sum${sum}`]();
<input type="text" value="1" id="duration" />
<input type="text" value="1000" id="sum_insured2" />

That being said, this is not a good pattern to follow. In your case I'd suggest executing a single statically defined function which handles the values of the inputs, whatever they may be.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

What about trying this:

console.log('show_d' + dur.toString() + '_sum' + sum.toString());

In order to create a method dynamically by this name try this:

var name = 'show_d' + dur.toString() + '_sum' + sum.toString();

var f = new Function('name', 'return alert("hello world");');

and call the method using f()

If you have already a method in your window with the same name then try accessing it like this:

window[name](anyArguments);
Deepak Singh
  • 610
  • 1
  • 7
  • 23