ronell
ronell

Reputation: 27

How can I call a function using a string in javascript?

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

Upvotes: 0

Views: 60

Answers (5)

Pawan
Pawan

Reputation: 1075

Please look in to following

var fn = window["test"];
if(typeof fn == 'function') {
    fn();
}

Upvotes: 1

Dmitry Masley
Dmitry Masley

Reputation: 525

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

Upvotes: 0

fagerli
fagerli

Reputation: 1

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

Upvotes: 0

try like this

<script>

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

Upvotes: 0

Sergei Beregov
Sergei Beregov

Reputation: 738

Eval is what you need. Example:

<script>
    eval("alert('hello')");
</script>

Upvotes: 0

Related Questions