1

i created an exercise program that create a dynamic menu from json. and then, everytime i clicked that dynamic menu, a tab will appear having a tab name depending on what is the name of the tab you are clicking.

what i want now, that i'm still figuring out, is that everytime i clicked the menu, it will call a function which have the same name of the menu i clicked., but i just dont know how to do it. my js functions is a separate file. here's the code:

    ....
    $('.menu').click(function () {
       dyna_tabs.add('Tab' + $(this).attr("rel"),  //this is for the <a href= "-">
       $(this).attr("rel"),                         //this if for the title
       $(this).html());                             // for the tab_content
       fname = $(this).html();                     // this is my variable name which i plan to use as function name
       alert('this would be my function name ' + fname);
       fname();
    }); 
    ....

you can find the rest of the dynamic tab code here. i just did some edit that would create a menu then tab from the menu.

so... i type fname(); where fname holds the value of the supposedly my function name. but everytime i run my program, an error message shows "fname is not a function". can anybody here knows how to do this right? please....

and one more thing, is anybody knows how put some html codes inside my dynamic tab.? or a .html page inside it? thank you for reading

jayAnn
  • 827
  • 3
  • 18
  • 38

2 Answers2

3

You can use another function that will call the necessary function. Like:

loader(fname);

function loader(s) {
  switch(s) {
    case 'xy': xy(); break;
    ...
  }
}

Your other option might be to store your functions in an object:

var myFunctions={
  'xy' : function () {
    //do something here
  },
  ...
};

and then you can call them easily like:

myFunctions[fname];

These are not complete solutions, just some guidelines that you could follow. The advantage over eval is that with these solutions it cannot happen that a function you have not intended to run could run. Only the predefined ones can be called.

kapa
  • 77,694
  • 21
  • 158
  • 175
  • @ bazmegakapa, thank you on this. this works. i just have to learn more on how to do it with more arguments (if its possible). by the way, is it ok to put a function inside a switch? thanks a lot bazmegakapa – jayAnn Mar 25 '11 at 02:34
  • function inside a switch, SOLVED. now is how to add my jqgrid from a html file inside my dynamic tab, in another html file...hmmm.. – jayAnn Mar 25 '11 at 02:59
  • you are always free to ask your next question ;) – kapa Mar 25 '11 at 07:22
1

I will apologize for this in advance.

eval(fname + '()');

should work

According to this question (How to execute a JavaScript function when I have its name as a string) there are some better alternatives.

Community
  • 1
  • 1
Oscar
  • 766
  • 1
  • 6
  • 13