4

We written some function in jquery.When user click on each div we need to call each function dynamically.

   <div class="test" id="test1"></div>
   <div class="test" id="test2"></div>


function test1(){
   alert('test1');
   }

   function test2(){
   alert('test2');
   }


   $(".test").on("click",function(){

   var function_name=$(this).attr("id");
    window[function_name]();

   });

But this code is not working end the error is window[function_name] is not a function . How to solve this

also Please suggest another 2,3 methods

5 Answers5

1

You can simply use window, It will work fine

function test1(){
   alert('You clicked on Test1');
   }

   function test2(){
   alert('You clicked on  Test2');
   }


   $(".test").on("click",function(){

   var function_name=$(this).attr("id");
   
     var call_myFun = window[function_name];
     
    call_myFun()
   });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test" id="test1">Test 1</div>
   <div class="test" id="test2">Test 2</div>

And You can do this way also..

$(".test").on("click",function(){

   var function_name=$(this).attr("id");
   eval(function_name + "()");

   });

function test1(){
   alert('clicked on test1');
   }

   function test2(){
   alert('clicked on test2');
   }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test" id="test1">test1</div>
   <div class="test" id="test2">test2</div>
Phani Kumar
  • 141
  • 5
  • The question solution work and no need to new solution. See https://jsfiddle.net/duevvfx8/ – Mohammad Nov 05 '16 at 09:45
  • alert("window[function_name]" )==[object HTMLImageElement] , and call_myFun() is not a function –  Nov 05 '16 at 09:48
0

instead of

var function_name=$(this).attr("id");
function_name();

use

var function_name=$(this).attr("id");
eval(function_name+"()");

see example https://jsfiddle.net/f6z04dfq/

Praveen Rawat
  • 724
  • 2
  • 12
  • 29
  • thank you . it is working . I will up vote you , when i get 15 points . :) . Could you please suggest other methods. changing the div structure or code is not a problem –  Nov 05 '16 at 09:27
  • see another method in @prasad's answer, why you downvoted my answer? – Praveen Rawat Nov 05 '16 at 09:29
  • 1
    Eval is a bad solution, it is better to avoid it if it possible, and in this case it is. – Mario Santini Nov 05 '16 at 09:29
  • 1
    why eval is bad ? –  Nov 05 '16 at 09:36
  • @MarioSantini it could be bad solution but its working and also one of the method to solve the above problem. – Praveen Rawat Nov 05 '16 at 09:37
  • @PraveenRawat http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string see the link – prasanth Nov 05 '16 at 09:39
  • @prasad but i think eval is not evil – Praveen Rawat Nov 05 '16 at 09:41
  • @John for a lot of reasons. It is slow and create many security concerns. For example, here it looks not dangerous, but what if I can inject my function and change an id to execute my malicius function? It is bad practice, when you debug you are not sure what this line of code do until you check the string, and many other reasons. It is not someting not useful or wrong, just it is better to avoid it if you can. – Mario Santini Nov 05 '16 at 09:45
  • @Mario is right, attacker can sniff clients cookie too. – Govinda Sakhare Nov 06 '16 at 12:38
0

On my point of view the approach to the problem is wrong.

If you have an id on your div you could bind the proper function to the event you desire.

That is the simple and effective solution to your problem.

The advantage on readability and maintainability is huge.

For example: what if some one in the future will change the name on a function in a way that the id don't match any more?

It is not easy to find the piece of code where the function is dynamically called.

So here is my proposal:

function test1() {
  console.log("Click on DIV 1");
}

function test2() {
  console.log("Click on DIV 2");
}

$(function(){
    $('#test1').click(test1);

    $('#test2').click(test2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="test" id="test1">Test 1</div>
<div class="test" id="test2">Test 2</div>
Mario Santini
  • 2,905
  • 2
  • 20
  • 27
  • 1
    thank you fro this suggestion . May be i have 100 div's . So in order to avoid $('#id').click(function); in 100 times i written the code . –  Nov 05 '16 at 09:34
  • 1
    @John if your case is to handle the click event on many different divs, this is a different problem. For example, if the code of *function 1* and *function n* are similar, and are different only for data, than you could refactoring one function to fit all your cases. If this is the case, please update your question and I'll update my answer accordingly. Can't do it now as I don't have enough information. – Mario Santini Nov 05 '16 at 09:50
0

you can call dynamic function using call method.

window[fun].call();

so in your case

$(".test").on("click",function(){
   var function_name=$(this).attr("id");
   window[function_name].call();
});
Veer
  • 6,046
  • 1
  • 14
  • 12
  • window[function_name].call is not a function –  Nov 05 '16 at 09:32
  • @Veer can you send me a link of example of this window[fun].call(); – Praveen Rawat Nov 05 '16 at 09:45
  • @PraveenRawat http://testrepo.skyptech.com/dynamiccall.php check this link i dont have document as such but i am using this in my projects – Veer Nov 05 '16 at 09:57
  • @john i try to test in jsfiddle but some how its not working there but you can check with this link http://testrepo.skyptech.com/dynamiccall.php – Veer Nov 05 '16 at 10:01
0

Umm.. You can create summary function to all your divs :

JQuery:

function xDiv(e){
    var i = $(e).attr("id");
    switch (i){
        case "test1":
             //Call matching function
            break; 
        case "test2":
            //Call matching function
            break; 
        case "test3":
            break;
        /*...*/
        default:
            break;
    }
     alert("This call from: " + i );
}

**HTML: **

<div id="test1" onclick="xDiv(this);">test1</div>
<div id="test2" onclick="xDiv(this);">test2</div>
<div id="test3" onclick="xDiv(this);">test3</div>
<div id="test4" onclick="xDiv(this);">test4</div>