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 😀