0

I'm already aware that there's a similar question about this but seems cant make it to work.

Please let me know what needed to do.

example: ( where the string "test" is the function name )

 <script>

  function test(){
  alert("Hello World");
  }
   //is this the right way to call it? 
  window["test"]();


  </script>

//no eval pls

ronell
  • 27
  • 7
  • [This answer](http://stackoverflow.com/a/359910/1270789) demonstrates how to do it. Please describe why you can't get it to work, including any JavaScript console errors. – Ken Y-N Sep 17 '13 at 07:39
  • It does not work in fiddle. I'm testing in fiddle at the moment when I asked this question. – ronell Sep 18 '13 at 00:54

5 Answers5

1

Please look in to following

var fn = window["test"];
if(typeof fn == 'function') {
    fn();
}
Pawan
  • 1,065
  • 5
  • 10
  • @ronell Please see modified answer – Pawan Sep 17 '13 at 07:22
  • Hi Pawan, I'm expecting an alert when I reload the page. Here's the fiddle: http://fiddle.jshell.net/uxskW/3/ – ronell Sep 17 '13 at 07:27
  • Please see the fiddle http://fiddle.jshell.net/uxskW/5/ You have to write this is head section and remove one extra = which i put by mistake , silly typo ;) – Pawan Sep 17 '13 at 07:36
0

Eval is what you need. Example:

<script>
    eval("alert('hello')");
</script>
Sergei Beregov
  • 738
  • 7
  • 19
0

try like this

<script>

function test(){
alert("Hello World");
}
var func = 'test'
this[func]();
</script>
0

Your example should work. Here is is an answer to a similar question How to execute a JavaScript function when I have its name as a string

Community
  • 1
  • 1
  • yeah, but it didn't work.. I already checked the page before asking. Thanks for the comment. – ronell Sep 17 '13 at 07:30
0

Pawan's answer is right, it doesn't work in fiddle because fiddle wraps code into $(window).on("load") event. Try it in normal page. Sorry, can't coment, low reputation

Dmitry Masley
  • 525
  • 4
  • 9