Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Using a variable as a function name

Tags:

html

jquery

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 call a function, instead of using an if statement. Example below:

function validate(thisInput){
    var thisClass = thisInput.attr("class").split(' ')[0];
    validate + class(thisInput); 
    /*This is what I would like to happen:
    the class is grabbed from above, then that class name (whatever it is)
    calls it's own function.  I will be creating a function for each class.
    */
}

function validateClassname(thisInput) {
    //do something
}

As you can see, I am trying to find the class name, make it into it's own function (without using if statements to drive it) then have that function do whatever it needs to do.

Am I looking at this wrong? Should I be going about it a different way? Thank you

like image 872
ntgCleaner Avatar asked Mar 18 '13 17:03

ntgCleaner


2 Answers

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 */ }
}

function validate(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.

like image 61
JJJ Avatar answered Sep 27 '22 23:09

JJJ


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.

like image 27
jsanc623 Avatar answered Sep 27 '22 23:09

jsanc623