Reputation: 287
This question is based on Get selected variation price in jQuery on Woocommerce Variable products.
I have some code that works on the single product page to display a calculated price based on user input. The problem is that the calculated price also applies to the related products on the bottom of the page. Their price is set to be the same as the product being viewed.
I think the problem lies in the line $('.price').html(total_pris+',-'); where '.price' applies to the related products also. How do I fix this?
My code:
add_action( 'woocommerce_before_add_to_cart_quantity', 'func_option_valgt'
);
function func_option_valgt() {
global $product;
if (has_term('endene','product_cat')){
$variations_data =[]; // Initializing
// Loop through variations data
foreach($product->get_available_variations() as $variation ) {
// Set for each variation ID the corresponding price in the data array (to be used in jQuery)
$variations_data[$variation['variation_id']] = $variation['display_price'];
}
?>
<script>
jQuery(function($) {
var jsonData = <?php echo json_encode($variations_data); ?>,
inputVID = 'input.variation_id';
$('input , #id_dropdown_one_end, #id_dropdown_other_end').change( function(){
if( '' != $(inputVID).val() ) {
var vid = $(inputVID).val(), // VARIATION ID
length = $('#rope_length').val(), // LENGTH
diameter = $('#diameter').val(), // DIAMETER
ene_enden = $('#id_dropdown_one_end').find('option:selected').attr("value_one_end"),
andre_enden = $('#id_dropdown_other_end').find('option:selected').attr("value_other_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 ene_enden_conv = Number(ene_enden);
var andre_enden_conv = Number(andre_enden);
var rope_price = (length*vprice) + ene_enden_conv + andre_enden_conv;
var total_pris = rope_price;
if (rope_price != 0){
$('.price').html(total_pris+',-');
}
}
});
}
});
});
</script>
<?php
}
}
Upvotes: 1
Views: 248
Reputation: 253919
To avoid updating related product prices too, you just need to make a little change replacing:
$('.price').html(total_pris+',-');
by:
$('.woocommerce-variation-price > .price').html(total_pris+',-');
This should solve your problem.
Upvotes: 1