5

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

ntgCleaner
  • 5,865
  • 9
  • 48
  • 86
  • 3
    Why not pass the class name to a generic validateName function? – Brad M Mar 18 '13 at 17:53
  • I will have to then create if-statements to make it decide what the class is before I can then run it's own function - I'm just trying to cut off the middle mane (if-statements) – ntgCleaner Mar 18 '13 at 17:57

2 Answers2

7

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.

JJJ
  • 32,902
  • 20
  • 89
  • 102
  • Thank you! I will be trying this out. With these inputs, there are strict rules outlining the validation class will be the first class, which is covered with the .split() – ntgCleaner Mar 18 '13 at 19:07
  • Thank you, I was looking for a way to cut out a middle man and make the code look prettier – ntgCleaner Mar 18 '13 at 21:40
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.

jsanc623
  • 534
  • 4
  • 17