0

It seems that in jquery click event you can only pass anonymous function. It is not possible to pass a normal javascript function. This lead to problems in my code.

function funcCancelClose(testcaseId,update)
{
   if(update == false)
   {
        modalCloseCancel(testcaseId);
   }
   else
   {
        modalCloseCancelUpdate(testcaseId, $("#radio-previous_"+testcaseId).val());
   }
}

var testcaseId = 891;
var update = false;

$("#modalCancel,#modalClose").click(funcCancelClose(testcaseId,update));

This did not work. Even there is no error message in developer console, behavior of code was wrong

5
  • 2
    You're calling the function immediately, not passing a function to call when the click happens. Commented Nov 25, 2019 at 17:54
  • Possible duplicate of Calling a function in jQuery with click() Commented Nov 25, 2019 at 17:56
  • ok so what is the syntax to have it called when the click happens ? Commented Nov 25, 2019 at 17:58
  • yeah you are right it is called immediately. That is wrong of course Commented Nov 25, 2019 at 18:05
  • It's funny if I pass it as normal function it gets executed, but if I pass it as anonymous function it gets not executed immediately. Why ist that ? Commented Nov 25, 2019 at 18:18

2 Answers 2

0

You get your values at html attr like that

<span id="modalCancel" data-attr-testcaseId="1" data-attr-update="0"><span>
$("#modalCancel").click(funcCancelClose);
function funcCancelClose(){ console.log($(this).attr('data-attr-testcaseId')); };
Sign up to request clarification or add additional context in comments.

1 Comment

Ok. So I have to use a trick to use it as I like to . I have to use a fake html element and put my values there. Hm...
0

What you wrote is calling funcCancelClose() immediately, and passing its value as the argument to click().

You can use an anonymous function or use the bind() function.

$("#modalCancel,#modalClose").click(function() {
    funcCancelClose(testcaseId,update);
});

$("#modalCancel,#modalClose").click(funcCancelClose.bind(null, testcaseId,update));

4 Comments

aha ok. So still I do not understand why normal function is executed immediately but anonymous function is not. But simply I think that is just Jquery implemenation. Right ?
how come I can call bind on a normal javascript function. What is parameter null . Yeah this works. Thanks.
It's like the difference between console.log(1+2) and console.log(function() { return 1+2; }). A function expression just creates a function, it doesn't execute it.
The first argument to .bind() is the value to be given to this in the function. It's null because your function doesn't use this.

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.