jquery dynamic function

12,774

Solution 1

You want to dynamically call foo or bar?

function callMethod(method)
{
     method();
}

callMethod(foo); // foo is the symbol for your method
callMethod(bar); // etc

At a high level. In your instance, though, you're asking to use that symbol as just a variable in your selector:

function callMethod(elementPrefix)
{
    $('#' + elementPrefix+ '_elem').toggle(true).attr('required', true);
    alert('This is ' + elementPrefix);
}

If you want to use it both as a string value, and the method name, you can eval the symbol to get the method:

var methodName = 'foo';
var text = 'This is ' + methodName; // This is foo
var method = eval('(' + methodName + ')');
method(); // calls foo()

Solution 2

I'm not sure if I understood your question fully, but do you want to dynamically create a function based on some arguments? If so, you could do something like this:

function make_func(x) {
  return function() {
    $("#"+x+"_elem").toggle(true).attr('required', true);
    alert('This is '+x);
  };
}

Then make_func('foo') would return a function which is equivalent to the function foo in your original example.

Share:
12,774
Phill Pafford
Author by

Phill Pafford

Love development with PHP/Symfony/PHPStorm, iOS, PostgreSQL, Linux flavor Ubuntu, jQuery/Mobile, Foundation CSS, GitFlow AVH and HTML5 Personal Projects are Crypto Currencies, Home Automation, Mobile development, SMS/MMS and DIY electronics via Make and Hack A Day https://keybase.io/phillpafford https://onename.com/phillpafford #bitcoin: https://www.coinbase.com/phillpafford #DogeCoin: D67fwUKwKQQeL9pdbZmbWcevuAYW8XPqyz

Updated on August 20, 2022

Comments

  • Phill Pafford
    Phill Pafford almost 2 years

    I just need the logic and understanding on how I can do this.

    The problem:

    I have several functions that are very similar but I want to create/call the dynamically

    Example:

    $(document).ready(function() {         
        function foo() {
            $("#foo_elem").toggle(true).attr('required', true);
            alert('This is foo');
        }
    
        function bar() {
            $("#bar_elem").toggle(true).attr('required', true);
            alert('This is bar');
        }
    });
    

    How can I pass in foo/bar to create the function? Pseudo code

    $(document).ready(function() { 
        // would pass foo/bar to this?        
        $($x)(function() {
            $("#"+$(this)+"_elem").toggle(true).attr('required', true);
            alert('This is '+$(this));
        });
    });