How to change price dynamically on product page in Magento2

In this blog post, we are going to code how to dynamically change the price on product page for magento 2.

To add JS code on the product page, we have created layout file and added js file in content reference container.

<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceContainer name="content">
        <block class="Magento\Framework\View\Element\Template"
               name="pricechange" as="pricechange" template="Codedecorator_Learn::product/js.phtml"/>
    </referenceContainer>
</page>

After creating layout file, lets create template file which will have our js code

require(["jquery","Magento_Catalog/js/price-utils"], function(jQuery,priceUtils) {
    var productPrice = parseFloat(jQuery('span.price-final_price > span[data-price-type="finalPrice"]').attr('data-price-amount'));
    var finalPrice=100;
    formatedPrice = priceUtils.formatPrice(parseInt(finalPrice));
    jQuery('span.price-final_price > span.price-wrapper > span.price').text(formatedPrice);
    var finalPrice=productPrice+(pricePerText*textObjects)+(pricePerImage*imageObjects);
    formatedPrice = priceUtils.formatPrice(parseInt(finalPrice));
    jQuery('span.price-final_price > span.price-wrapper > span.price').text(formatedPrice);
}); // Required

After creating both the files, just flush the cache using following command.

php bin/magento cache:flush

I hope this post will help and give the solution for any of your problem.

happy coding 😀

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

Leave a Reply

Your email address will not be published.