I am using opencart 3.x and trying to get the price into a number so I can do calculations with it. I keep getting NaN or a scripting error:
<h2><span id="getPrice">{{ price }}</span> /Carton</h2>
Here I set id as getPrice, so I can get the price once the page loads, it comes out to $169.99. This number cannot be utilized as a number..this is the issue I am having. I know the { { price } } is PHp I believe, but I think since the number loads before my script, I don't have to worry about it? Once the page loads, it says $116.99 /per carton, I spanned out the { { price } } so I can turn just that into a number.
Here is my javascript. i tried parsefloat which doesnt work, and toFixed(2) which alawys gets the " toFixed is not a function" error
const getPrice = document.querySelector("[id^='getPrice']").innerHTML;
const getSquareFeetPerBox = document.querySelector("[id^='input-option']").value;
const costPerSqft = getPrice / getSquareFeetPerBox;
const fixxed = parseFloat(getPrice);
document.getElementById("pricePerSqft").innerHTML = ` ( ${costPerSqft} /per sqft )`;
console.log(fixxed);
Please help, I have been at this for hours and just need to do a simple calculation with the price. I'm using console.log just to see if a number is logged but its always $116.99 or script error...never just 116.99
I thank you in advance
Assuming the following HTML:
<h2><span id="getPrice">$169.99</span> /Carton</h2>
<input type="text" id='input-option' value="10"></input>
<p id="pricePerSqft"> </p>
With the following JS:
const getPrice = document.querySelector("[id^='getPrice']").innerHTML;
const getSquareFeetPerBox = document.querySelector("[id^='input-option']").value;
const fixed = parseFloat(getPrice.slice(1, getPrice.length));
const costPerSqft = fixed / getSquareFeetPerBox;
console.log(costPerSqft)
document.getElementById("pricePerSqft").innerHTML = ` ( ${costPerSqft} / per sqft );
You should be able to parse the number. I used String#slice to grab the number but per the comments on your original post there are definitely other ways to grab the number. Using a regex like Mark suggested sounds like a solid option :)
CodePen link here if you need it: https://codepen.io/travishaby/pen/jRbqMr