首页 > 解决方案 > How to clear form input on page load woocommerce checkout

问题描述

I am offering customers a repurchase on the order confirmed page. If they click the link they are sended directly to the checkout page. However, the form is then prefilled with the previous data. I would like to clear it, because the idea is one product(ticket) per person.

So far i have the following (and in the page source i can see the script is loaded):

function print_script() {

if (isset($_GET['extrapersoon']) && is_page(21560)){

    echo '<script>
window.addEventListener("load", function(){myFunction()};

function myFunction() {
  document.getElementsByClassName("woocommerce-checkout").reset(); 
}
</script>';
        }
  }
add_action('wp_print_scripts', 'print_script');

I tried other triggers too, such as window.load but no result yet.

Anyone?

标签: wordpressformswoocommerce

解决方案


You should put the script in the footer using add_action( 'wp_footer', 'print_script' ); to make sure the form gets cleared after the data was loaded into it.

Wordpress has jQuery on default, so I'm using it to look for all the forms in the document and clear them. The function is automatically called on page load, therefore no need for a event listener.

<?php
function print_script() { 
    if (isset($_GET['extrapersoon']) && is_page(21560)) { ?>
        <script type="text/javascript">
            ( function( $ ) {
                $('form').each(function() { this.reset() });
            }( jQuery ) );
        </script>
    <?php }
}
add_action( 'wp_footer', 'print_script' ); ?>

推荐阅读