How to calculate an amount with commas - javascript

I have a product that cost 1,500.85 and i want to multiply it with the quantity input using javascript. But because the amount is over a thousand there is a comma and because of that comma the result shown "NaN" .. How do i calculate the amount with the comma?
NOTE: It works if the amount is under a thousand.
// Calculation script START
$(document).ready(function() {
CalculateTotalPrice();
});
document.getElementsByClassName("input-text qty text")[0].onkeyup = function() {CalculateTotalPrice()};
$(select).onchange(function() {
CalculateTotalPrice();
});
function CalculateTotalPrice() {
setTimeout(function(){
var price = document.querySelector(".price .woocommerce-Price-amount.amount").innerText;
var quantity = document.getElementsByClassName("input-text qty text")[0].value;
var total = price * quantity;
var totalOnly2Decimal = total.toFixed(2);
document.getElementById("result").innerHTML = "DKK " + totalOnly2Decimal + " inkl. moms";
}, 100);
}
// Calculation script END
<!-- Price -->
<div class="elementor-widget-container">
<p class="price">Fra:
<span class="woocommerce-Price-amount amount">
<span class="woocommerce-Price-currencySymbol"></span>1,122.50
</span> kr. inkl. moms</p>
</div>
<!-- Quantity field -->
<div class="quantity">
<label class="screen-reader-text" for="quantity_5cd3fab7bb0d7"></label>
<input type="number" id="quantity_5cd3fab7bb0d7" class="input-text qty text" step="1" min="1" max="" name="quantity" value="1" title="Stk." size="4" inputmode="">
<!-- Result -->
<h3 style="font-size: 17px; font-weight:bold; display:inline; text-transform:uppercase;">Total:</h3>
<p class="result" id="result" style="display:inline;"></p>

Replace all the commas using String.prototype.replace then multiply.
let price = '1,500.85';
let quantity = '7';
let total = price.trim().replace(/,/g, '') * quantity;
console.log(total)

You can remove the comma with the replace method on the String object and convert to integer
price = parseInt(price.replace(/,/g,''))
var total = price * quantity;

Change this line to the following
var price =
document.querySelector(".price .woocommerce-Price-amount.amount").innerText.split(",").join("");
// Calculation script START
$(document).ready(function() {
CalculateTotalPrice();
});
document.getElementsByClassName("input-text qty text")[0].onkeyup = function() {
CalculateTotalPrice()
};
function CalculateTotalPrice() {
setTimeout(function() {
var price = document.querySelector(".price .woocommerce-Price-amount.amount").innerText.split(",").join("");
var quantity = document.getElementsByClassName("input-text qty text")[0].value;
var total = price * quantity;
var totalOnly2Decimal = total.toFixed(2);
document.getElementById("result").innerHTML = "DKK " + totalOnly2Decimal + " inkl. moms";
}, 100);
}
// Calculation script END
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Price -->
<div class="elementor-widget-container">
<p class="price">Fra:
<span class="woocommerce-Price-amount amount">
<span class="woocommerce-Price-currencySymbol"></span>1,122.50
</span> kr. inkl. moms</p>
</div>
<!-- Quantity field -->
<div class="quantity">
<label class="screen-reader-text" for="quantity_5cd3fab7bb0d7"></label>
<input type="number" id="quantity_5cd3fab7bb0d7" class="input-text qty text" step="1" min="1" max="" name="quantity" value="1" title="Stk." size="4" inputmode="">
<!-- Result -->
<h3 style="font-size: 17px; font-weight:bold; display:inline; text-transform:uppercase;">Total:</h3>
<p class="result" id="result" style="display:inline;"></p>
<script>
</script>

There seemed to be a couple of errors with your snippet that i've done my best to fixup below. To answer your question, there are two main points:
var priceAsFloat = parseFloat(price.replace(/,/g, ''));
Remove the comma from the price and then convert it to a float before doing any maths with it
var result = totalOnly2Decimal.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
Convert the result back to a string and use the above regex to put commas back in at the desired points.
Working example:
// Calculation script START
$(document).ready(function() {
CalculateTotalPrice();
});
document.getElementsByClassName("input-text qty text")[0].onkeyup = function() {CalculateTotalPrice()};
$("input").change(function() {
CalculateTotalPrice();
});
function CalculateTotalPrice() {
setTimeout(function(){
var price = document.querySelector(".price .woocommerce-Price-amount.amount").innerText;
var priceWithoutCommas = price.replace(/,/g, '');
var quantity = document.getElementsByClassName("input-text qty text")[0].value;
var total = priceWithoutCommas * quantity;
var totalOnly2Decimal = total.toFixed(2);
var result = totalOnly2Decimal.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
document.getElementById("result").innerHTML = "DKK " + result + " inkl. moms";
}, 100);
}
// Calculation script END
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Price -->
<div class="elementor-widget-container">
<p class="price">Fra:
<span class="woocommerce-Price-amount amount">
<span class="woocommerce-Price-currencySymbol"></span>1,122.50
</span> kr. inkl. moms</p>
</div>
<!-- Quantity field -->
<div class="quantity">
<label class="screen-reader-text" for="quantity_5cd3fab7bb0d7"></label>
<input type="number" id="quantity_5cd3fab7bb0d7" class="input-text qty text" step="1" min="1" max="" name="quantity" value="1" title="Stk." size="4" inputmode="">
<!-- Result -->
<h3 style="font-size: 17px; font-weight:bold; display:inline; text-transform:uppercase;">Total:</h3>
<p class="result" id="result" style="display:inline;"></p>

Related

how to Print out variable?

I'm really new to JS. I am working on the if else statement and returning the total using the button. I also want to return some other input from HTML file also using the same button or on the same function as my calculate function. How do I return the total amount, name(input), number(input), from html to that one button as well?
If you don't get my question please run the code and see that it is not printing out the other input value. Thank you for helping me out.
function calculate() {
var total
var kwh = parseFloat(document.getElementById("kw").value);
if (kwh <= 50) {
total = (kwh * 500);
} else if (kwh <= 100) {
total = kwh * 1000;
} else {
total = kwh * 2120;
}
document.getElementById("total").innerHTML = total;
}
<body>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input id="name" type="text" placeholder="ឈ្មោះអតិថិជន">
</div>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input type="number" placeholder="លេខអតិថិជន">
</div>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input type="number" placeholder="kwh" id="kw">
</div>
<button type="button" onclick="calculate()">គណនា</button>
<p>Result: <span id="total"></span></p>
<p>Name: <span id="name"></span></p>
<!-- <script src="script2.js"></script> -->
</body>
You are very close just need a few tweaks.
You shouldn't repeat ids, so in that case, to make it easier to understand, we can rename the input with id name to name_input, so you can retrieve its value as
document.getElementById('name_input').value
You can add that to your function and assign it to the innerHTML of name inside the function calculate() and so on with as many actions as you want
Working snippet:
function calculate() {
var total
var kwh = parseFloat(document.getElementById("kw").value);
if (kwh <= 50) {
total = (kwh * 500);
} else if (kwh <= 100) {
total = kwh * 1000;
} else {
total = kwh * 2120;
}
document.getElementById("total").innerHTML = total;
document.getElementById("name").innerHTML = document.getElementById("name_input").value;
}
<body>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input id="name_input" type="text" placeholder="ឈ្មោះអតិថិជន">
</div>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input type="number" placeholder="លេខអតិថិជន">
</div>
<div>
<label>ឈ្មោះអតិថិជន:</label>
<input type="number" placeholder="kwh" id="kw">
</div>
<button type="button" onclick="calculate()">គណនា</button>
<p>Result: <span id="total"></span></p>
<p>Name: <span id="name"></span></p>
<!-- <script src="script2.js"></script> -->
</body>

Why document.getElementById().value returns a string even though its type is Number?

I am trying to make a tip calculator and the total variable returns a string because typeof bill is a string, why is it so, even though the text input box type is number?
output("bill entered is 1000 and no of person is 1):- string
150
150
1000150
document.querySelector('#persons').addEventListener('change', (findresult));
document.querySelector('#bill').addEventListener('change', (findresult));
document.querySelector('#percent').addEventListener('change', (findresult));
function findresult() {
var persons = document.getElementById('persons').value;
var bill = document.getElementById('bill').value;
var percent = document.getElementById('percent').value;
// console.log(persons);
console.log(typeof bill);
// console.log(percent);
var tip = (bill * percent) / 100;
var tip_person = tip / persons;
var total = bill + tip;
console.log(tip);
console.log(tip_person);
console.log(total);
}
<div class="container">
<h1>Tip calcuator</h1><br>
<div class="inputs">
<input type="number" class="inputfield" id="persons" placeholder="No of Persons"><br><br>
<input type="number" class="inputfield" id="bill" placeholder="Bill"><br><br>
<input type="number" class="inputfield" id="percent" placeholder="Tip%">
</div>
<br>
<div class="result">
<br>
<p>Tip Per Person :</p>
<p>TOTAL :</p>
</div>
</div>
Surround the bill, percent declaration values with parseFloat to allow for decimals while converting the value String to a Number.
var bill = parseFloat(document.getElementById('bill').value);
var percent = parseFloat(document.getElementById('percent').value);
You may allow decimals in the Number Input by using the step attribute and set it to 0.01. This will affect the values created when using the up,down button on the Input.
<input type="number" class="inputfield" id="bill" placeholder="Bill" step="0.01" >
document.querySelector('#persons').addEventListener('change', (findresult));
document.querySelector('#bill').addEventListener('change', (findresult));
document.querySelector('#percent').addEventListener('change', (findresult));
function findresult() {
var persons = document.getElementById('persons').value;
// Use parseFloat to allow for decimals
var bill = parseFloat(document.getElementById('bill').value);
var percent = parseFloat(document.getElementById('percent').value);
// console.log(persons);
console.log(typeof bill);
// console.log(percent);
var tip = (bill * percent) / 100;
var tip_person = tip / persons;
var total = bill + tip;
console.log(tip);
console.log(tip_person);
console.log(total);
}
<div class="container">
<h1>Tip calcuator</h1><br>
<div class="inputs">
<input type="number" class="inputfield" id="persons" placeholder="No of Persons"><br><br>
<!-- Allow cents to be allowed via the `step` attribute -->
<input type="number" class="inputfield" id="bill" placeholder="Bill" step="0.01" ><br><br>
<input type="number" class="inputfield" id="percent" placeholder="Tip%">
</div>
<br>
<div class="result">
<br>
<p>Tip Per Person :</p>
<p>TOTAL :</p>
</div>
</div>
User parseInt(), it will convert string into number.
function findresult() {
var persons = parseInt(document.getElementById('persons').value);
var bill = parseInt(document.getElementById('bill').value);
var percent = parseInt(document.getElementById('percent').value);
// console.log(persons);
console.log(bill);
// console.log(percent);
var tip = (bill * percent) / 100;
var tip_person = tip / persons;
var total = bill + tip;
console.log(tip);
console.log(tip_person);
console.log(total);
}
As mentioned by #Heretic Monkey, the input element has a property valueAsNumber and since the input type is always a number, we wouldn't have to worry about the parsing.
so we can use document.getElementById('persons').valueAsNumber
Also a few suggestions, it's always nice to break your code in smaller parts. Therefore separating the logic of fetching the input values and performing calculations separately will be a better approach and its not a good practice to call the DOM objects repeatedly.
For example, we can create a function for change event listener and read the event argument and update the necessary object of values,
document.querySelector('#persons').addEventListener('change', (update));
document.querySelector('#bill').addEventListener('change', (update));
document.querySelector('#percent').addEventListener('change', (update));
let values = {
persons: 0,
bill: 0,
percent: 0,
}
function update(event) {
values[event.currentTarget.id] = event.target.valueAsNumber;
findresult();
}
Finally, you can read the values as follows,
var persons = values["persons"];
var bill = values["bill"];
var percent = values["percent"];
So putting all together,
document.querySelector('#persons').addEventListener('change', (update));
document.querySelector('#bill').addEventListener('change', (update));
document.querySelector('#percent').addEventListener('change', (update));
let values = {
persons: 0,
bill: 0,
percent: 0,
}
function update(event) {
values[event.currentTarget.id] = event.target.valueAsNumber;
findresult();
}
function findresult() {
var persons = values["persons"];
var bill = values["bill"];
var percent = values["percent"];
var tip = (bill * percent) / 100;
var tip_person = tip / persons;
var total = bill + tip;
console.log(tip);
console.log(tip_person);
console.log(total);
}
<div class="container">
<h1>Tip calcuator</h1><br>
<div class="inputs">
<input type="number" class="inputfield" id="persons" placeholder="No of Persons" step="0.01"><br><br>
<input type="number" class="inputfield" id="bill" placeholder="Bill"><br><br>
<input type="number" class="inputfield" id="percent" placeholder="Tip%">
</div>
<br>
<div class="result">
<br>
<p>Tip Per Person :</p>
<p>TOTAL :</p>
</div>
</div>
Hope it helps.

Add an input value to a database value

I am working on a project where I have to add a database value to in input value.
<div>
<div class="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
</div>
In above code 680 will come from the database. Here I want to add an input number to that 680. I am very new to jQuery.
My JavaScript code is
$(document).ready(function() {
var total = 0;
$("input").keyup(function(){
var priceList = $('.price');
$.each(priceList, function(i, price){
total += parseFloat($(price).text());
});
alert(total);
});
});
</script>
In this it outputs "NaN".
In this it outputs "NaN".
You get this message since you're trying to loop through div's and parsing the text of them, when it's empty. You need to loop over input's instead.
You could init the total with the database value then loop through the input's and add the parsed values to total in every iteration.
NOTE: Use input event instead when you track the user input since it's more efficient.
Multiple inputs:
$(document).ready(function() {
var db_val = parseFloat($('.price:first').text());
var total = 0;
$(".price input").on('input', function() {
var total = db_val;
$('.price input').each(function() {
total += parseFloat($(this).val()) || 0;
});
$(".total").text(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="total">680</div>
</div>
Single input:
$(document).ready(function() {
var db_val = parseFloat($('.price:first').text());
var total = 0;
$(".price input").on('input', function() {
var total = db_val;
total += parseFloat($(this).val()) || 0;
$(".total").text(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="price">680</div>
<div class="price">
<input type="number" name="name">
</div>
<div class="total">680</div>
</div>
Here you go
var result = 0;
var price = +$('#price').text();
$('input[type="number"]').on('input', function() {
var val = +$(this).val();
result = parseInt(val + price);
$('#price').text(result)
console.log(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="price" id="price">680</div>
<div class="price">
<input type="number" name="name">
</div>

Javascript - Count of characters in a textfield returning NaN

I have a form I am trying to do, where if some one inputs text in a text field of a form, then clicks submit, I want to show him the cost of the sign (charactercount x price) i keep getting NaN!
Heres my Html:
<section class="sign" id="sign">
<h3 class="sign_header">CUSTOM SIGNAGE</h3>
<p class="sign_text">Enter Name, the cost per letter is $<span id="lettercost">6</span>.</p>
<form class="info_form">
<input type="text" id="inputletters" value="Example Name"><br>
<input type="button" value="Submit" class="button" id="getprice" onClick="getPrice();">
</form>
and here is my Javascript
function getPrice(){
var quantity = document.getElementById('inputletters').value.length;
var price = document.getElementById('lettercost');
var total = quantity*price;
var cost = document.getElementById('cost');
cost.textContent = total;
}
Here's a runnable example -- price was an object, you want .textContent, and parse those into numbers for this to work.
function getPrice() {
var quantity = document.getElementById('inputletters').value.length;
var price = document.getElementById('lettercost').textContent;
console.log(typeof quantity, typeof price)
var total = Number(quantity) * Number(price);
var cost = document.getElementById('cost');
cost.textContent = total;
}
<section class="sign" id="sign">
<h3 class="sign_header">CUSTOM SIGNAGE</h3>
<p class="sign_text">Enter Name, the cost per letter is $<span id="lettercost">6</span>.</p>
<form class="info_form">
<input type="text" id="inputletters" value="Example Name"><br>
<input type="button" value="Submit" class="button" id="getprice" onClick="getPrice();">
</form>
<div id="cost"></div>
</section>

Calculating price from <span> value and <input> value

Today I try to calculating the price from <span> value and <input> value. And then, put the result in <span>.
I already tried this code. This is my html:
<td class="cart-product-price">
<span id="price" class="amount">19.99</span>
</td>
<td class="cart-product-quantity">
<div class="quantity clearfix">
<input type="button" value="-" class="minus" field="quantity">
<input type="text" id="quantity" name="quantity" value="2" class="qty" />
<input type="button" value="+" class="plus" field="quantity">
</div>
</td>
<td class="cart-product-subtotal">
<span id="total" class="amount"></span>
</td>
So I want to get price value from <span id="price>, get quantity from <input type="text" id="quantity" name="quantity">, and put the result in <span id="total" class="amount"></span>
This is my script code:
<script type="text/javascript">
var price = parseFloat($('#price').val()) || 0;
var qty = parseInt($('input[name=quantity]').val());
var total = price*qty;
$('#total').text(total);
</script>
Note: I am using JQuery for increase / decrease quantity (plus & minus button)
Did I wrote something wrong?
Thanks
UPDATE
This is my increase / decrease javascript code:
<script type="text/javascript">
jQuery(document).ready(function(){
// This button will increment the value
$('.plus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[name='+fieldName+']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
// This button will decrement the value till 0
$(".minus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
});
</script>
The 'price' field is a span, which do not have a value property. Instead, you need to read the text() from it. Also note that the 'quantity' field has an id, so you would be better to use that as a selector as it's much faster. Try this:
var price = parseFloat($('#price').text()) || 0;
var qty = parseInt($('#quantity').val());
var total = price * qty;
$('#total').text(total);
Working example
var price = parseFloat($('#price').text()) || 0; //parseFloat($('#price').val()) || 0;
var qty = parseInt($('input[name=quantity]').val());
var total = price * qty;
$('#total').text(total);
The .val() method is primarily used to get the values of form elements such as input , select and textarea
FIDDLE DEMO
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<style>
.active {
color:red;
}
</style>
<script>
$(document).ready(function () {
var price = parseFloat($('#price').text()) || 0;
var qty = parseInt($('input[name=quantity]').val());
var total = price * qty;
$('#total').text(total);
});
</script>
</head>
<body>
<table>
<tr>
<td class="cart-product-price">
<span id="price" class="amount">19.99</span>
</td>
<td class="cart-product-quantity">
<div class="quantity clearfix">
<input type="button" value="-" class="minus" field="quantity">
<input type="text" id="Text1" name="quantity" value="2" class="qty" />
<input type="button" value="+" class="plus" field="quantity">
</div>
</td>
<td class="cart-product-subtotal">
<span id="total" class="amount"></span>
</td>
</tr>
</table>
</body>
</html>

Categories

Resources