2

Explaining by example:

$(".myCheckboxes").click(function () {
    ...
});

Inside the click event function I have code that does various things depending on what checkboxes are checked.

I however need to run this code to initialize it first, kindof like this:

$(".myCheckboxes").click(function () {
    ...
}).click();

It runs the code and it gets initialized, but it also clicks on all my checkboxes making them all invert their value.

Is it possible to execute the inline click event function wihtout executing a click event?

I would very much like to keep the function inline to keep the flow of the code. Also, it's not big enough to have the function outside of the event, but it's not so small as I would like to write the code twice.

3
  • Right now you're using an anonymous function. But couldn't you define a function (function foo(){...}) and then call it before assigning it as the click event listener? ($(".myCheckboxes").click(foo());) Commented Nov 6, 2015 at 14:19
  • 1
    @thanksd wouldn't that bind the return value of foo as the handler for the click event? Commented Nov 6, 2015 at 14:21
  • @taxicala yeah should be this: $(".myCheckboxes").click(foo);) Commented Nov 6, 2015 at 17:27

3 Answers 3

5

triggerHandler triggers only the handler:

$(".myCheckboxes").click(function () {
    ...
}).each(function(i, checkbox) { 
    $(checkbox).triggerHandler('click'); 
}

Note that you need to iterate the checkboxes if you wish to trigger the handler for all of them instead of just the first one:

while .trigger() will operate on all elements matched by the jQuery object, .triggerHandler() only affects the first matched element.

Sign up to request clarification or add additional context in comments.

3 Comments

So, if there are 10 checkboxes, the handler will be executed 10 times.
@taxicala, yes, if the asker doesn't want that they need to leave out the iteration (like in Andrea Carron's answer).
Only need it once as I'm doing the iteration inside the function as I need to count how many have been clicked. And this works great - Thanks!
5

Use a named function as the handler, bind it and execute it:

$(".myCheckboxes").click(clickHandler);
clickHandler();

1 Comment

This is a (possibly the) solution, but does that mean that the answer to the question is "No, you can't execute the inline function"?
2

You may consider to call the function triggerHandler who seems to do what you need.

$(".myCheckboxes").click(function () {
...
}).triggerHandler('click');

NB: I haven't tested this solution.

Comments

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.