Search code examples
javascriptmootools

Calling javascript code contained in a variable


I have the below anchor tag

<a rel="2" onclick="javascript:aimsCCUAQuestionsBanner('TOPIC','VAC_FIOSTV_PROD_AVAIL','CPTU');" name="&amp;lid=choose_topic_fiostvchangeservice" id="opt1tv1" href="javascript:void(0);" class="tv-avail">Billing </a>

No whenever "Billing" is clicked I have to call aimsCCUAQuestionsBanner('TOPIC','VAC_FIOSTV_PROD_AVAIL','CPTU'). Also when the user clicks on another hyperlink present on the same page, the onclick function has to be read and executed the same like how its called when "Billing" is clicked.

Im reading the onclick function using mootools into a variable like below

var func = $("step-1").getElement('a#'+step1_id).get('onclick');

But when Im trying to execute the function like below

  window[func](); 

The function is not being called in both FF and IE. Can someone tell me how to execute the function from the variable?


Solution

  • Do eval of the function

    eval(func);
    

    Try http://jsfiddle.net/99MrC/1/ for example

    Update:: What your trying to do is getting the attribute value of anchor tag which is "javascript:aimsCCUAQuestionsBanner('TOPIC','VAC_FIOSTV_PROD_AVAIL','CPTU');" This will be a string and not function. So you need to eval for browser to execute the string as javascript.

    When you said this is working

    var func = aimsCCUAQuestionsBanner('CHANGE_CATEGORY','VAC_MAIN', '');
    func();
    

    that is because when you executed

    var func = aimsCCUAQuestionsBanner('CHANGE_CATEGORY','VAC_MAIN', '');
    

    it already executed the function.

    The next call

    func();
    

    supposed to fail because it is not function, unless your function returns another function