SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot
    Join Date
    Aug 2011
    Location
    Trinidad and Tobago
    Posts
    194
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Calling a function based on a string

    So I have a string which I want to use to call a function. How can I do this?. For example lets say I have a string = "function1". Now since I have this string I to use it to call
    Code:
    function function1();
    to execute it within my application. Note that sometimes I may have a string which will be arguments to call another function for example, string = function2,1,2. This will call
    Code:
    function function2(1,2)
    . Any idea on how I can do this?

  2. #2
    SitePoint Addict
    Join Date
    Dec 2005
    Posts
    336
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    You can use window[string](); like the example below:

    Code:
    function test() {
    	alert('Function called!');
    }				
    
    var str = 'test';
    window[str]();

  3. #3
    Non-Member
    Join Date
    Apr 2011
    Location
    no fixed address
    Posts
    851
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by skelleex View Post
    Note that sometimes I may have a string which will be arguments to call another function for example, string = function2,1,2. This will call
    Code:
    function function2(1,2)
    . Any idea on how I can do this?
    In this case you will need to split() the string into an array of its components. The first element of the array will be the function name and the other elements will be the arguments. Insert the argument elements in the () of

    window[strSplit[0]]();

  4. #4
    SitePoint Zealot
    Join Date
    Aug 2011
    Location
    Trinidad and Tobago
    Posts
    194
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    excellent these responses work perfectly thanks alot


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •