skip to Main Content

I’m adding javascript code to a woocommerce wordpress website.

The code is simple. What does is, when the user clicks on a div area of the checkout page, the code makes it click on the submit button as well.

What I did was add this code php to my functions.php file:

add_action("wp_enqueue_scripts", "jm_insertar_js3");
    function jm_insertar_js3(){
        if (is_checkout()){
            wp_register_script('miscript3', get_stylesheet_directory_uri(). '/script3.js', array('jquery'), microtime(true), true );
            wp_enqueue_script('miscript3');
        }
    }

And then, I created this file (script3.js):

window.onload = function(){
    var div3 = document.querySelectorAll('div.mp-row-checkout');
    for (var i = 0; i < div3.length; i++) {
        div3[i].onclick = function() {
        document.getElementById("place_order").click();
        }
    }
}

In fact, when I try this code in the browser console:

    var div3 = document.querySelectorAll('div.mp-row-checkout');
    for (var i = 0; i < div3.length; i++) {
        div3[i].onclick = function() {
        document.getElementById("place_order").click();
        }
    }

Everything works perfectly.

The problem is that when I try the code normally nothing happens (when I click the div area the code don’t run), and I have to Empty Cache and Hard Reload to make it works. I just don’t know why or how can I fix this.

I disable all type of cache server-side and website-side. I’m doing the test from an incognito tab to avoid cache. And finally, I add a timestamp (microtime(true)) to the version of the file to avoid browsers from caching and the issue still persist.

I’m not a programmer, so any information will help.

Thanks in advance.

2

Answers


  1. Chosen as BEST ANSWER

    I decided to change the trigger event. window.onload generates issues.

    Final JS file (script3.js):

    var div3 = document.querySelectorAll('div.woocommerce-billing-fields, input.input-text ');
    for (var i = 0; i < div3.length; i++) {
        div3[i].onclick = function() {
            var idNuevo = document.getElementById("jm-mp-row-checkout");
            if (!idNuevo) {
                document.getElementsByClassName("mp-row-checkout")[0].setAttribute("id", "jm-mp-row-checkout");
                document.getElementById("jm-mp-row-checkout").addEventListener("click", myFunctionJM2);
                function myFunctionJM2() {
                    document.getElementById("place_order").click();
                }
            }
        }
    }
    

  2. For preventing from browser cache for js file. We can add a query string. like

    /script3.js?qid=currentTimeStamp

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search