0

I am looking to call a onclick function forcefully.

$('.checkbox-selector').click(function() {

});

$('.checkbox-selector1').click(function() {

});

When a control goes to the first function, the second function should be called automatically i.e. onlick event is triggered.

2
  • 1
    Just as an aside, you can block your code with four spaces, as opposed to back ticks, for syntax highlighting. Commented Aug 3, 2012 at 9:30
  • 1
    Did you use the search before you asked this question? Commented Aug 3, 2012 at 9:32

3 Answers 3

3
function func1(e) {
    // do stuff for selector

    // run func2 too!
    func2();
}

function func2(e) {
    // do stuff for selector1
}

$('.checkbox-selector').click(func1);
$('.checkbox-selector1').click(func2);

Is this what you mean?


If so, make sure to look at the comments! They contain quite valuable information considering events and such.

You can replace func2(); with $('.checkbox-selector1').trigger('click'); to trigger the native event handler too! Using $('.checkbox-selector1').triggerHandler('click'); is practically the same as func2();, whichever you prefer.

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

7 Comments

This is much better solution seeing as .trigger("click") will call the native .click() method on the element which could have other side effects. See what I mean here: jsfiddle.net/8Kfmd/1 . In chrome the second checkbox gets checked as a result of what I just explaind.
@Esailija, It's not a (negative) side effect if you ask me. It entirely depends on the project but if you want to mimic a user click having a checkbox actually checked is 100% correct imo.(that aside, writing clean functions for this is often nicer)
Well the op didn't mention anything about needing to check the checkbox, just calling another function where .trigger is inappropriate.
I have to admit, I miss read that part at first. But without knowing the full context of the code trigger can still be a good option.(+1 on this answer from me too because of how it often should be coded)
@Esailija: If you only wanted to call event handers bound by jQuery, you could use .triggerHandler: api.jquery.com/triggerHandler.
|
1

Take a look at the jQuery trigger function

Comments

0

Not sure what it is exactly you're looking for, but I'd guess:

$('.checkbox-selector').click(function() {
    /* all sorts of stuff*/
    $('.checkbox-selector1').click();
    //or:
    $('.checkbox-selector1').trigger('click');
});

$('.checkbox-selector1').click(function() {

});

Something like that?

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.