1

I want to fire a HTML button click event by clicking another button, Can anyone help me with the code, I'm using jQuery library..

4 Answers 4

3

You mean something like this?

$('#button1').click(function() {
    $('#button2').click();
});

If click is called without passing an argument, it will trigger the click event on that element.

Documentation is helpful.

Update regarding your comment:

Have you had this problem? My small tests show that the code is executed in order, meaning, code after triggering the click is executed after the click handler. But maybe my handler is not complex enough...

If you indeed experience problems, you could put all the code that is executed in the #button2 click handler in its own function and call this one in the #button1 click handler:

function lotsOfWork() {

}

$('#button2').click(lotsOfWork);

$('#button1').click(function() {
    lotsOfWork();
    // more stuff here
});

If lotsOfWork is doing some asynchronous calls you also have to make the function accept a callback that will be executed after it finishes its work.

1
  • The main problem is I need to wait until the code execution of button2 is complete then I need to continue some code for button 1, If I write this code I cannot wait until the code execution of button2 is complete..
    – Sandeep
    Apr 9, 2011 at 9:38
1

try something like this:

<input type="button" id="btn1" value="click A">
<input type="button" id="btn2" value="click B">
<script>
$(function(){
    $('#btn1').click(function(){
        $('#btn2').trigger('click');
    })
})
</script>

to fire events of other objects you just have to call the .trigger method, passing the event name that you pretend to fire.

1
$('#buttonone').click(function(){
  $('#buttontwo').trigger('click')
})

Clicking on buttonone will trigger a click on buttontwo

0
$(function(){
    $("#id_btn").click(function(){
                call your function for 2nd button
    });
});
or
$('#id_btn').bind('click', function() {
    $('#id_btn').trigger('click');
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.