Price calculation based on dimensions in WooCommerce single product page

后端 未结 1 1460
轮回少年
轮回少年 2021-01-18 18:20

Based on \"Get selected variation price in jQuery on Woocommerce Variable products\" answer code,
in my code bellow, I have a problem with the price calculation

1条回答
  •  臣服心动
    2021-01-18 19:07

    Because you are concatenating strings. Is not the same 1 + 0 than "1" + "0", as you can check here:

    console.log("1 + 0 =", 1 + 0);
    console.log('"1" + "0" =', "1" + "0");

    When you get a value from an HTML object, you receive it as a string. If you want to use it as a number you must convert it before. You can use either Number or parseFloat (even parseInt, but will remove decimals).

    var oneNumber = 1;
    var oneString = "1";
    var oneConverted = Number(oneString);
    
    console.log("typeof oneNumber:", typeof oneNumber);
    console.log("typeof oneString:", typeof oneString);
    console.log("typeof oneConverted:", typeof oneConverted);
    
    console.log("oneNumber + oneNumber =", oneNumber + oneNumber);
    console.log('oneString + oneString =', oneString + oneString);
    console.log('oneConverted + oneConverted =', oneConverted + oneConverted);

    The exact problem you are having is your ene_enden variable being a string in the line var rope_price = (length*vprice) + ene_enden;. When you multiply two strings, they are automatically converted to a number (your (length*vprice)), but when you concatenate that number to another string, they are converted automatically to a string again (your + ene_enden), so you must first convert ene_enden to a number, ot better convert all expected number variables to a number.

    0 讨论(0)
提交回复
热议问题