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

2
  • This answer demonstrates how to do it. Please describe why you can't get it to work, including any JavaScript console errors. Commented Sep 17, 2013 at 7:39
  • It does not work in fiddle. I'm testing in fiddle at the moment when I asked this question. Commented Sep 18, 2013 at 0:54

5 Answers 5

1

Please look in to following

var fn = window["test"];
if(typeof fn == 'function') {
    fn();
}
Sign up to request clarification or add additional context in comments.

3 Comments

@ronell Please see modified answer
Hi Pawan, I'm expecting an alert when I reload the page. Here's the fiddle: fiddle.jshell.net/uxskW/3
Please see the fiddle fiddle.jshell.net/uxskW/5 You have to write this is head section and remove one extra = which i put by mistake , silly typo ;)
0

Eval is what you need. Example:

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

1 Comment

Thank you for the comment, but I don't want to use eval.
0

try like this

<script>

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

Comments

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

1 Comment

yeah, but it didn't work.. I already checked the page before asking. Thanks for the comment.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.