I have a WooCommerce based shop, and I am trying to implement some event tracking based on user actions.
I would like to run a custom JS function when the user clicks on the Place order button, which is the final step before paying.
This is the code of the button:
<button type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="Place order" data-value="Place order">Place order</button>
In my script I have this:
jQuery(document).ready(function ($) {
// here are some other handlers
$("#place_order").click(() => {
alert("click");
});
});
When I log the result of $("#place_order")
, it seems jQuery can find the element:
a.fn.init [button#place_order.button.alt, context: document, selector: "#place_order"]
But in the devtools window of google chrome, there’s no click handler for this button (under the Event Listeners tab) and the function is not ran.
I have other click events wired up in the very same document.ready function, in a similar way, which works just fine.
Add to cart button:
<button type="submit" name="add-to-cart" value="2819" class="single_add_to_cart_button button alt">Add to cart</button>
script:
$("button[name=add-to-cart]").on("click", () => {
console.log("product added to cart"); // This works fine and visible under Event Listeners tab
});
I’ve tried using the selector "button[name=woocommerce_checkout_place_order]"
and with .on("click")
too.
So what could be the reason my event listener for the place order button is not getting added, or is getting removed?
Is there a way I can check if handlers are removed from the button by other scripts? I’m thinking maybe WooCommerce removes it for some reason.
2
Answers
As for checkout “place order” submit event is delegated to the
<form>
by WooCommerce, you will need to delegate the click event to the<form>
too this way:Or the same thing embedded in a function (targeting checkout page):
Code goes in functions.php file of your active child theme (or active theme).
Now as you will see it works.
Related: jQuery – Understanding Event Delegation
as far as I have found, there are custom DOM events triggered by woocommerce that are messing with checkout elements, in order to set up listeners for the elements inside checkout you should wrap your listeners initialization in a function and hook the function both on init_checkout and updated_checkout events (for some reason found it working only with jQuery .on method).
Example:
A more direct answer to is that above mentioned events strip all listeners from the elements within checkout or just clones them, either way you need to re-hook your listeners after each of them.