How could I change the NaN text to 0?
Im using a function to show a variable price calculator in a Woocommerce store.
Until some variable are selected Im getting a NaN result, once selected it works fine so I would like to just change the NaN text to zero.
This is the code:
// hook this on priority 31, display below add to cart button.
add_action( 'woocommerce_single_product_summary', 'woocommerce_total_product_variation_price', 31 );
function woocommerce_total_product_variation_price() {
global $woocommerce, $product;
// setup base html... We are going to rewrite this with the standard selected variation
echo sprintf('<div id="product_total_price" style="margin-bottom:20px; display: block;">%s %s</div>',__('Precio Total:','woocommerce'),'<span class="price">'.$product->get_price().'</span>');
?>
<script>
jQuery(function($){
var currency = currency = ' <?php echo get_woocommerce_currency_symbol(); ?>';
function priceformat() {
var product_total = parseFloat(jQuery('.woocommerce-variation-price .amount').text().replace(/ /g ,'').replace(/€/g ,'').replace(/,/g ,'.')) * parseFloat(jQuery('.qty').val());
var product_total2 = product_total.toFixed(2);
var product_total3 = product_total2.toString().replace(/./g, ',');
jQuery('#product_total_price .price').html( currency + ' ' + product_total3);
}
jQuery('[name=quantity]').change(function(){
priceformat();
});
jQuery('body').on('change','.variations select',function(){
priceformat();
});
priceformat();
});
</script>
<?php }
Thanks in advance
2
Answers
Just check if the variable is NaN and if it is set it to zero.
A simpler way to do this is:
Because
product_total
isNaN
it will assign it to0
. Be careful though because0
is also considered afalsey
value in this scenario.