0

I try to write a function to show/hide Add to cart button (WooCommerce) when the price of product is zero - 0,00 €. When the page loads and the product has this zero price it should hide the product Add to cart button and when I chose an option and the price change, for example to 30,00 €, then it should show the button. In console.log() I see the prices change but the condition to show/hide the button doesn't work.

var zeroVal = "0,00 €",
    newVal = jQuery('.price').text();
jQuery('.price').change(function(){
    if(newVal == zeroVal) {
     jQuery('.single_add_to_cart_button').attr("style","display: none!important");
   } else {
     jQuery('.single_add_to_cart_button').attr("style","display: block!important");
   }
});

function priceChangeListener() {
   if(newVal != zeroVal) {
     newVal = jQuery('.price').text();   
   }
   jQuery('.price').change();
};
setInterval(priceChangeListener, 500);

What do I do wrong? Is there any simpler solution? I was not able to find any. Thanks for any help provided.

Roman
  • 1
  • 1
  • Move `newVal = jQuery('.price').text();` into your `change` event handler – Ryan Wilson Oct 21 '22 at 19:25
  • what do you see in the console log when you log both price at each interval? – Arif Oct 21 '22 at 19:25
  • @RyanWilson this I tried, now I get in console log (index):774 Uncaught ReferenceError: newVal is not defined – Roman Oct 22 '22 at 17:04
  • @Arif in the console log I see the price changes as I select the options, however the condition doesn't take an effect – Roman Oct 22 '22 at 17:06

1 Answers1

0

I'm wondering if the problem might be caused by your implementation of the .attr() method.

According to the jQuery API Docs, to set a simple attribute, the first argument to the .attr() method should be the name of the attribute and the second should be the desired value.

Ex. $( "#greatphoto" ).attr( "alt", "Beijing Brush Seller" );

To set multiple attributes at once, an object should be passed in containing key-value pairs, the keys being the name of the attribute and the value being the value.

Ex. $( "#greatphoto" ).attr({ alt: "Beijing Brush Seller", title: "photo by Kelly Clark" });

Additionally, this stackoverflow post provides alternative methods of showing/hiding elements that might be useful. Namely, the .hide() and .show() methods, along with the .css() jQuery method.

Hope that helps.

Kat
  • 1
  • 2