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 of a WooCommerce variable product.
The price gets multiplied with 10 or 1000, depending on the option selected on a dropdown, which is not supposed to happen and I don't know why it is happening.
Here is my code:
<script>
jQuery(function($) {
var jsonData = <?php echo json_encode($variations_data); ?>,
inputVID = 'input.variation_id';
$('input').change( function(){
if( '' != $(inputVID).val() ) {
var vid = $(inputVID).val(), // VARIATION ID
length = $('#cfwc-title-field').val(), // LENGTH
diameter = $('#diameter').val(), // DIAMETER
ene_enden = $('#id_dropdown_one_end').find('option:selected').attr("value_one_end"),
vprice = ''; // Initilizing
// Loop through variation IDs / Prices pairs
$.each( jsonData, function( index, price ) {
if( index == $(inputVID).val() ) {
vprice = price; // The right variation price
}
});
var rope_price = (length*vprice) + ene_enden;
if (rope_price != 0){
$('.price').html(rope_price+',-');
}
alert('variation Id: '+vid+' || Lengde: '+length+' || Diameter: '+diameter+' || Variantpris: '+vprice+ ' || Rope price: '+rope_price+' || ene_enden = '+ene_enden);
}
});
});
</script>
For some reason rope_price gets multiplied by 10 or concatenated with 0 when the option selected for 'I enden av tauet ' is 'Ingenting'(it's value is 0). When I change the option selected to any of the others rope_price gets multiplied with 1000 or concatenated with 00. I don't know why this is happening. Any ideas?
Because you are concatenating strings. Is not the same
1 + 0
than"1" + "0"
, as you can check here: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
orparseFloat
(evenparseInt
, but will remove decimals).The exact problem you are having is your
ene_enden
variable being a string in the linevar 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 convertene_enden
to a number, ot better convert all expected number variables to a number.