0

I have function name in a var,

var i = 2; // iteration
var fname = 'myFunction' + i; // looks like myFunction2()

now i want to assign this function on element's event. i.e.

var elem = document.getElementById('e');
elem.onclick = fname;

It doesn't work. JS take function name as 'fname()' not the string inside it 'myFunction2()'

A little help would be appriciated,

Thanks in advance.

Ali Nawaz Hiraj
  • 122
  • 1
  • 6

2 Answers2

1

You can do this

window['myFunction' + i]

or create a array/object of functions.

var i = 2; // iteration
var fname = 'myFunction' + i; // looks like myFunction2()
var elem = document.getElementById('e');
elem.onclick = window[fname];
cocco
  • 16,442
  • 7
  • 62
  • 77
-1

Check these answers: Javascript - Variable in function name, possible? and Use JavaScript variable as function name?

What you attempt is to assign a string (variable) on an event.

Community
  • 1
  • 1
Leon
  • 919
  • 6
  • 21