Skip to content Skip to sidebar Skip to footer

Jquery: Using A Variable As A Function Name

I am trying to make a function that calls other functions depending on the class of an element that I am interacting with. I would like to be able to use the class of an element to

Solution 1:

Am I looking at this wrong?

Yes. Here's a more sensible approach with objects (foo and bar are the class names):

var validationRules = {
    foo: function( input ) { /* whatever */ },
    bar: function( input ) { /* whatever */ }
}

functionvalidate(thisInput){
    var thisClass = thisInput.attr("class").split(' ')[0];

    validationRules[ thisClass ]( thisInput );
}

Also, you might want to reconsider using class names to store information. If there are more than one class it's not guaranteed that the one you want is the first one. Look into data attributes instead.

Solution 2:

You can use the eval() function to evaluate a variably named function:

var className = "OnName";
var classType = "OnType";

eval("validate" + className + "()")
// calls validateOnName()eval("validate" + classType + "()")
// calls validateOnType()var someInput = 234;
eval("validate" + classType + "(" + someInput + ")")
// calls validateOnType(234)

Not that this is an ideal solution - and perhaps you should be thinking about using a generic function or group of functions than to have multiple functions for multiple class names.

Post a Comment for "Jquery: Using A Variable As A Function Name"