I have a calculator that is meant to calculate prices in Dollars and Euros and the biggest issue I'm facing here is the fact that using a comma as a decimal separator does not work with the <input type='number'>
tag. I have read that browser language determines how this particular input type responds, but I was wondering if there was a way to alter that with JS.
function pplCalculator() {
let endprice = document.getElementById('ppl-calculator--endprice');
let margin = document.getElementById('ppl-calculator--margin');
let basePrice = document.getElementById('ppl-calculator--val');
let locale = document.querySelector('html').getAttribute('lang');
let config = {
dollar: {
retailDefault: 18.99,
basePrice: 13.99,
},
euro: {
retailDefault: 19.99,
basePrice: 14.99
}
}
let currency = locale === 'en-US' ? 'dollar' : 'euro';
function calculatorInit(){
endprice.value = config[currency].retailDefault;
basePrice.textContent = config[currency].basePrice;
margin.textContent = (endprice.value - basePrice.textContent).toLocaleString(locale);
}
function updateCalculator(target, events, handler){
events.map(function(event){
target.addEventListener(event, () => {
let userInput = endprice.value;
let marginValue = userInput - basePrice.textContent;
if (marginValue > 0) {
margin.textContent = marginValue.toLocaleString(locale);
} else {
margin.textContent = 0;
}
});
})
}
calculatorInit();
updateCalculator(endprice, ['keyup','change']);
}
pplCalculator();
This is my HTML
<table>
<tr>
<td><strong>Retail Price</strong></td>
<td><input id="ppl-calculator--endprice" type="number"></td>
</tr>
<tr>
<td><strong>Profit</strong></td>
<td><p id="ppl-calculator--margin"></p></td>
</tr>
<tr>
<td><strong>Base Price</strong></td>
<td><p id="ppl-calculator--val"></p></td>
</tr>
</table>
The page has a language switcher that uses OctoberCMS's activeLocale to change the language attribute in my HTML tag. The locale
var uses that information.
The actual calculation works fine, but I can't seem to figure out how to switch to EU formatting for the Euros both on the input and in the Init function. Using element.toLocaleString()
creates a string (which is fine for displaying output), but obviously does not work with input.
What would be the best way to accommodate both decimal separators?
I also want to add; I would like to avoid having to build a spinner box to increase and decrease the numbers if at all possible hence the Number input field instead of Text. If it is completely unavoidable, I suppose it's the way to go, but I wanted to double check first.