0

I have some functions defined inside a array like this.

checkInputType : function(sel){
 alert($(sel).prop('type'));
},
checkSelect : function(el){
 .......
},
.....

And I can call it like this options.checkInput($(this));. This is working.
Now I want to call any of those defined functions dynamically. So I have this array with the function names in it.

var elmType2Func = {'input' : 'checkInput', 'select' : 'checkSelect', 'textarea' : 'checkTextarea'};

Now looping through all elements inside a form I want to call the right function for each element(elmType2Func array with element as a key and function name as a value).

var element = $(this).prop('tagName').toLowerCase();

I cannot call like this - options.elmType2Func[element]($(this)); I know this is not the right way to call this function.
Can anybody help me with this.

1
  • Don't you just need to do options[elmType2Func[element]]($(this)); ? Commented Jan 31, 2014 at 8:52

3 Answers 3

3

You need to store functions, not their names:

var elmType2Func = {'input' : checkInput, 'select' : checkSelect, 'textarea' : checkTextarea};

http://jsfiddle.net/hmb25/

If the functions are already members of some object, like:

var options = {
     checkInput: function() {...},
     checkSelect: function() {...},
}

then you can keep strings in elmType2Func:

var elmType2Func = {'input' : 'checkInput', 'select' : 'checkSelect', 'textarea' : 'checkTextarea'};

and use double indirection to refer to them:

var tag = $(this).prop('tagName').toLowerCase();
var fun = options[elmType2Func[tag]];

gives you a reference to the function.

Sign up to request clarification or add additional context in comments.

1 Comment

yes. The functions are already members of options object. Thanks. working perfectly...
2

Rather than putting a string for the name put the function

var elmType2Func = {
    'input' : checkInput,
    'select' : checkSelect, 
    'textarea' : checkTextarea,
    'submit' : function (arg) { ... }
};

Comments

2
options.elmType2Func[element]($(this));

That is accessing the property with the literal name elmType2Func on the object - you want to use bracket notation here as well:

options[elmType2Func[element]]($(this));

Alternatively, you might not use elmType2Func as a property name lookup table, but to look up the functions directly:

var elmType2Func = {
    'input' : options.checkInput,
    'select' : options.checkSelect, 
    'textarea' : options.checkTextarea
};
elmType2Func[element]($(this));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.