fightstarr20
fightstarr20

Reputation: 12578

jQuery trigger 2nd button when first is clicked

I am trying to trigger a second button click when the first one is clicked using jQuery, I have this..

jQuery( "#dup_button" ).click(function() {
    alert("Duplicate Button Pressed");
    jQuery("input[name='add-to-cart']").click();
});
    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="dup_button">
  Click Me
</button>

<button name="add-to-cart" class="single_add_to_cart_button button alt">Add To Cart</button>

Is this ok for a selector? Can I select the button by name like this?

Upvotes: 1

Views: 173

Answers (3)

Anupam Biswas
Anupam Biswas

Reputation: 66

jQuery("button[name='add-to-cart']").trigger( "click" );

Upvotes: 1

Victor Stoddard
Victor Stoddard

Reputation: 3721

jQuery( "#dup_button" ).click(function() {
    //alert("Duplicate Button Pressed");
    jQuery("button[name='add-to-cart']").click();
});

$("button[name='add-to-cart']").click(function() {
  alert( "Cart button clicked." );
});

https://jsfiddle.net/g5h9exp6/

Upvotes: 1

jonathanbell
jonathanbell

Reputation: 2627

If you are trying to fire a click event on the button, maybe use .trigger(), not click .click()

.click() registers what happens when the element is clicked (its click handler) but does not emit the click event.

You might also want to try "functionalizing" your code like:

function thing1() {
  // things happen
  alert("Duplicate Button Pressed");
}

function thing2() {
  // other things happen
}

jQuery("#dup_button").click(function() {
  thing1();
});

jQuery("input[name='add-to-cart']").click(function() {
  // any"thing" can happen! lol.
  thing1();
  thing2();
});

The above code allows for a little more flexibility. You can call thing1() or thing2() independently of each other or "at the same time".

Upvotes: 1

Related Questions