0

I have a button and I have function which should execute on click.

example:

<button id="button1">bla bla</button>

<script>
var justFunctionName = "function1";
var function1 = function()
{
alert("!");
}

$("#button1").click(justFunctionName);

</script>
Mediator
  • 14,951
  • 35
  • 113
  • 191

3 Answers3

2

HTML

<button id="button1">bla bla</button>


jQuery

var justFunctionName = "function1";

function function1()
{
    alert("!");
}

$("#button1").on("click", window[justFunctionName]);


See working jsFiddle demo

Community
  • 1
  • 1
Code Maverick
  • 20,171
  • 12
  • 62
  • 114
-1
$("#button1").click(justFunctionName);

should be

$("#button1").click(function1);
-1
var justFunctionName = "function1";

This is assigning the string function1 to the variable justFunctionName.

If you were to do: console.log('justFunctionName'); you would end up with the following result:

>function1

Therefore this variable assignment is completely irrelevant for what you are hoping to achieve. Instead of just assigning a variable to a function you are assigning a variable to a variable which is assigned to a function.


Now take a look at what you are doing here:

var function1 = function () {
  alert("!");
};

This is assigning a variable function1 to the function doing the alert. In this instance, think of the variable as a reference to the function. In order to have the button trigger the alert, you need to call the reference to the function (in this case function1):

$("#button1").click(function1);
Andrew Hill
  • 2,165
  • 1
  • 26
  • 39
  • He wants to be able to call a function only with a name, the answer of Code Maverick seems to do the tricks. I can see it comming handy if, for exemple, you need to call a certain function depending of an attribute, for exemple ValidatePhone() or ValidateEmail() depending of the type of an object instead of calling Validate() and having a switch case that determine wich function to call. – Shryme Jan 08 '14 at 16:44