'Woocommerce - Show total weight as quantity increases on archive

I found a code snippet on Regiel Gallarde's website that displays in a div the total price according to quantity field update. I used this as a base to write a snippet that does the same stuff but with the price and on the archive. I ended up with this:

add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_total_product_weight', 31 );
function woocommerce_total_product_weight() {
    global $woocommerce, $product;
    // let's setup our divs
    echo sprintf('<div id="product_total_weight" style="margin-bottom:20px;">%s %s</div>',__('Peso total:','woocommerce'),'<span class="weight">'.$product->get_weight().'</span>');
    ?>
        <script>
            jQuery(function($){
                const weight = <?php echo $product->get_weight(); ?>
                    /*weight_unit = get_option('woocommerce_weight_unit'),*/

                $('[name=quantity]').change(function(){
                    if (!(this.value < 1)) {

                        const product_total_weight = parseFloat(weight * this.value);

                        $('#product_total_weight .weight').html(product_total_weight.toFixed(2));

                    }
                });
            });
        </script>
    <?php
}

It manages to show the weight for each product on the archive page but crashes when I update the quantity selector.

Does anyone know what is wrong with my approach?

Thanks a lot in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source