phpwordpresswoocommerce

woocommerce confirmation message on order cancellation


hello i have this function which adds cancel button to my account-> orders list

    add_filter( 'woocommerce_valid_order_statuses_for_cancel', 'custom_valid_order_statuses_for_cancel',1, 2 );
function custom_valid_order_statuses_for_cancel( $statuses, $order ){

    // Set HERE the order statuses where you want the cancel button to appear
    return array_merge( $statuses, array('processing', 'shipped'));
}

i want to add a javascript confirmation message when he press the cancel button it ask (are you sure you want to cancel the order?)

how can i achieve that i tried putting the javascript inside the function but with no luck

HTML Code for the cancel button

    <td class="woocommerce-orders-table__cell woocommerce-orders-table__cell-order-actions" data-title="Actions">
                                                            <a href="http://localhost/zumra/wordpress/my-account/view-order/1028/" class="woocommerce-button button view">View</a><a 
href="http://localhost/zumra/wordpress/cart/?cancel_order=true&amp;order=wc_order_CvYEzh8G4OKJ8&amp;order_id=1028&amp;redirect=http%3A%2F%2Flocalhost%2Fzumra%2Fwordpress%2Fmy-account%2F&amp;_wpnonce=938ffd4571" class="woocommerce-button button cancel">Cancel</a><a href="/zumra/wordpress/my-account/orders/2/?bewpi_action=view&amp;post=1028&amp;nonce=17f4df17bd" class="woocommerce-button button invoice">Invoice</a>                                                    </td>

the javascript code :

    ( function($) {
  $("#s").autocomplete({
    source: product_lib.products_array
  });

  $('.woocommerce-button button cancel').click(function(e){
    e.preventDefault();
    if (confirm('are you sure?')) {
        $('#idOfTheForm').submit();
    }
});
document.getElementsByClassName('woocommerce-button button cancel').onclick = function() {
  preventDefault();
  alert("button was clicked");
}​;​

  window.onload = function() {
    if (window.location.href.indexOf("comment") > -1) {
      window.location.hash = "#tab-description";
      location.reload();
    }
  }

})(jQuery);


Solution

  • First Idea (without code) you have to put this inside any .js file which is loaded on the site where the cancel-button is printed. If you dont know which .js files are loaded: right click => inspect => network => reload page => filter by "js"

    If there isn´t any file you can edit, you can still put this js code inside a JS-HERE tag

    jQuery('#idOfCancelButton').click(function(e){
        if (!confirm('are you sure?') {
            e.preventDefault();
        }
    }
    

    New Idea

    instead of

    preventDefault();
      alert("button was clicked");
    

    do

    if (!confirm('Are you sure?')) {
        preventDefault();
    }