This question already has an answer here:
Javascript calculator keeps concatenating calculation results with first number entered for next calculation
(1 answer)
Closed 4 years ago.
I'm writing a program that takes two numbers, a subtotal and tax rate, and prints the sales tax and grand total. However, I've run into multiple problems writing it, so I've tried working backwards and dumbing it down to simply adding two numbers. Instead of adding the numbers, however, it is simply printing the two numbers side by side. Can anyone tell me what's wrong with my code?
https://codepen.io/anon/pen/jvNZox
HTML:
var subtotal = document.getElementById("subtotal");
var taxRate = document.getElementById("tax-rate");
var salesTax = document.getElementById("sales-tax");
var total = document.getElementById("total");
subtotal.addEventListener("input", calc);
taxRate.addEventListener("input", calc);
function calc()
{
var sub = (subtotal.value) || 0;
var tax = (taxRate.value) || 0;
total.innerHTML = sub + tax;
}
JS:
var subtotal = document.getElementById("subtotal");
var taxRate = document.getElementById("tax-rate");
var salesTax = document.getElementById("sales-tax");
var total = document.getElementById("total");
subtotal.addEventListener("input", calc);
taxRate.addEventListener("input", calc);
function calc()
{
var sub = (subtotal.value) || 0;
var tax = (taxRate.value) || 0;
total.innerHTML = sub + tax;
}
EDIT: My bad, forgot to add parseFloat before my value checks. Same problem still stands for when I go back to my original code:
var subtotal = document.getElementById("subtotal");
var taxRate = document.getElementById("tax-rate");
var salesTax = document.getElementById("sales-tax");
var total = document.getElementById("total");
subtotal.addEventListener("input", calc);
taxRate.addEventListener("input", calc);
function calc()
{
var sub = parseFloat(subtotal.value) || 0;
var tax = parseFloat(taxRate.value) || 0;
salesTax.innerHTML = sub * (tax /100);
total = sub + salesTax.innerHTML;
}
You're bumping into the fact that the values are strings, and you can use + to concatenate strings as well as add up numbers.
Parse the number strings into actual Numbers first:
function calc()
{
var sub = parseFloat(subtotal.value || 0);
var tax = parseFloat(taxRate.value || 0);
total.innerHTML = sub + tax;
}
You need to take the numerical value of the strings by using an unary plus +, for example.
This approach has the advantage, if a nonconvertable string is supplied, a NaN value is taken as falsy value and together with logical OR ||, you get zero as default value.
var sub = +subtotal.value || 0;
var tax = +taxRate.value || 0;
JavaScript considers the values as two strings and thus combines them.
Do something like this:
var subtotal = document.getElementById("subtotal");
var taxRate = document.getElementById("tax-rate");
var total = document.getElementById("total");
subtotal.addEventListener("input", calc);
taxRate.addEventListener("input", calc);
function calc() {
var sub = Number(subtotal.value) || 0;
var tax = Number(taxRate.value) || 0;
total.innerHTML = sub + tax;
}
<p> Subtotal: <input id = "subtotal"></p>
<p> Tax Rate: <input id = "tax-rate"></p>
<p id = "total"></p>
Change the logic for addition to below as previously it was considering it as a JavaScript string and instead of summing it was concatenating it. Explicitly converting it to an integer/double will prevent this. '||' handles non-numeric data in text field.
var subtotal = document.getElementById("subtotal");
var taxRate = document.getElementById("tax-rate");
var salesTax = document.getElementById("sales-tax");
var total = document.getElementById("total");
subtotal.addEventListener("input", calc);
taxRate.addEventListener("input", calc);
function calc()
{
var sub = parseFloat(subtotal.value) || 0;
var tax = parseFloat(taxRate.value) || 0;
salesTax.innerHTML = sub * (tax /100);
total.innerHTML = sub + parseFloat(salesTax.innerHTML|| 0);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p> Subtotal: <input id = "subtotal"></p>
<p> Tax Rate: <input id = "tax-rate"></p>
Total: <p id = "total"></p>
Sales tax: <p id = "sales-tax"></p>
</body>
</html>
You need to cast string value to integer type. To do it you could use parseInt function:
total.innerHTML = parseInt(sub) + parseInt(tax);
Related
I have some problem with my js code which when I run the code it show me a NaN error, I have a function that calculate something.
Example:
<p id = "total "></p>
total = num1 *num2;
document.getElementById("total").innerHTML = total;
And it works fine but when I create a new function to calculate the discount
var price = document.getElementById("total").value;
discount = total *0.10;
It shows a NaN, I tried a lot of solution but it is still not working.
Can you help me?
I think you have a concept mistake, if the value is a HTML value, i mean, is inside of
<p id="this_is_the_element">123456789</p>
You can get that value with javascript using the
var number = document.getElementById('this_is_the_element').innerHTML
now the number variable will have inside "123456789" as a STRING
But if you are using an input you should use
var number = document.getElementById('this_is_the_element').value
Now, try this. First try to avoid the parseInt, instead use Number.
Define a function
var discount = function(){
var price = Number(document.getElementById("total").innerHTML);
return price*0.1;
}
If you want to do it on new sintax use this
const discount = () => {
const price = Number(document.getElementById("total").value);
return price*0.1;
}
There are few issues in your code:
There is no value property of p element. To access the text in p element, you can use either textContent or innerText.
By default the text is of type string. Multiplying string with number gives you NaN. You have to convert that to number before doing any arithmetic operation.
var num1 = 5;
var num2 = 20;
var total = num1 *num2;
document.getElementById("total").textContent = total;
var elTotal = Number(document.getElementById("total").textContent);
var discount = elTotal * 0.10;
console.log(discount)
<p id = "total"></p>
When you pull the value, it's a String, and JavaScript for the most part will automatically do type conversion, but you can always wrap it in parseInt to force it to be a Number.
discount = parseInt(total) * 0.10;
You can also always run typeof total to verify if total is a Number or String, and you can run console.log(total) to visually verify the contents.
Also, your document.getElementById("total") references a paragraph element, which doesn't have .value property, so you should use innerText to get its value instead.
Demo
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
button1.addEventListener('click', function() {
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
total = parseInt(num1) * parseInt(num2);
document.getElementById("total").innerText = total;
});
button2.addEventListener('click', function() {
var total = document.getElementById("total").innerText;
discount = parseInt(total) * 0.10;
document.getElementById('discount').innerText = discount;
});
<input type="text" id="num1" /><br>
<input type="text" id="num2" /><br>
<button id="button1">Add</button>
<p id="total"></p>
<button id="button2">Discount</button>
<p id="discount"></p>
Documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
Hello so I am trying to work on this code for my Java Script class and I am stuck on how to proceed. The instructions for the problem we were given were as follows:
Create a simple self-checkout system. Prompt for the prices and quantities of three items. Calculate the subtotal of the items. Then calculate the tax using a tax rate of 5%. Print out the line items with the quantity and total, and then print out the subtotal, tax amount, and total.
Here is my code so far:
// Make a function for a simple self-checkout system.
// prompt the user for quantity of the items
// Prompt the user for the prices of the items
function self_Checkout () {
var prices = [x, y, z,];
var x = prompt('Enter value');
var quantity_x = prompt('Enter value for quantity of item 1');
return x * quantity_x;}
{ if
var y = prompt('Enter value');
var quantity_y = prompt('Enter value for quantity of item 2');
return y * quantity_y;
{ if
var z = prompt('Enter value');
var quantity_z = prompt('Enter value for quantity of item 3');
return z * quantity_y;
// Multiply entire total by a tax rate of 5%
// Return value of total of all items + tax to user
// Use console.log or document.write?
}
Now the assignment also mentions how we are supposed to use loops objects and arrays also in this problem. I have attempted to add a array in the code. Some help on how to proceed in my code would be much appreciated, hopefully i explained it well enough to get some help.
Here is working code that is all dynamic and not limited to 3 items
<!DOCTYPE html>
<html>
<head>
<script>
function getit(){
var result = document.getElementById('demo');
var allitems = 0;
var itemCount = prompt("how many items do you need?");
var items = {};
for (i = 0; i < itemCount; i++) {
items[i] = {
name : prompt("Product Name"),
price : prompt("Product Price"),
qty : prompt("Product qty")
}
}
for (i = 0; i < itemCount; i++) {
var subtotal = 0;
var total = 0;
subtotal = items[i].price * items[i].qty;
total = subtotal * 1.05;
allitems = allitems + subtotal;
result.innerHTML += "Product: " + items[i].name + "<br/>";
result.innerHTML += "Total Qty: " +items[i].qty + "<br/>";
result.innerHTML += "Sub total: " + subtotal + "<br/>";
result.innerHTML += "Sub total: " + total + "<br/>";
if(i == (itemCount - 1)){result.innerHTML += "Sub total for all items: " + allitems + "<br/>";}
}
}
</script>
</head>
<body>
<button onclick="getit()">Shop</button>
<p id="result">Creating a JavaScript Object.</p>
</body>
</html>
I have a Javascript code as written below. Everything is working fine except the fact the net value that is the grand total of addition of all the total values, is coming as NaN. I have used parseFloat() but still the result is NaN. But I am getting the all the total values.
Any help is welcome.
window.onkeyup=function() {
var items = document.querySelectorAll(".item");
var itemsArray = Array.prototype.slice.call(items,0);
var unit, rate, total, net, tax, margin, rateamount = 0;
itemsArray.forEach(function(el){
unit = el.querySelector('input[name="unit[]"]').value;
rate = el.querySelector('input[name="rate[]"]').value;
tax = el.querySelector('input[name="tax[]"]').value;
margin = el.querySelector('input[name="margin[]"]').value;
el.querySelector('input[id="marginrate[]"]').options[el.querySelector('input[id="marginrate[]"]').selectedIndex].text;
var rateMargin =el.querySelector('[name="marginrate[]"]').selectedIndex;
if (rateMargin==1) {rateamount=margin/100}
if (rateMargin==0) {rateamount=margin}
total = (parseFloat(unit * rate) + parseFloat(rateamount))-parseFloat(tax/100);
alert(total);
el.querySelector('input[name="total[]"]').value = total;
net+= parseFloat(total);
});
document.getElementById('net').value=net;
}
You never initialized net, so when you do net += parseFloat(total); you're adding a number to undefined, which results in NaN. You need to initialize it to 0.
You also should be calling parseFloat on the values that are read from the inputs, not on the results of arithmetic operations (they always return numbers, you don't need to parse them).
window.onkeyup = function() {
var items = document.querySelectorAll(".item");
var itemsArray = Array.prototype.slice.call(items, 0);
var unit, rate, total, net = 0, tax, margin, rateamount = 0;
itemsArray.forEach(function(el) {
unit = el.querySelector('input[name="unit[]"]').value;
rate = el.querySelector('input[name="rate[]"]').value;
tax = el.querySelector('input[name="tax[]"]').value;
margin = el.querySelector('input[name="margin[]"]').value;
el.querySelector('input[id="marginrate[]"]').options[el.querySelector('input[id="marginrate[]"]').selectedIndex].text;
var rateMargin = el.querySelector('[name="marginrate[]"]').selectedIndex;
if (rateMargin == 1) {
rateamount = margin / 100
} else if (rateMargin == 0) {
rateamount = margin
}
total = (parseFloat(unit) * parseFloat(rate) + parseFloat(rateamount)) - parseFloat(tax) / 100;
alert(total);
el.querySelector('input[name="total[]"]').value = total;
net += total;
});
document.getElementById('net').value = net;
}
I am getting value using jquery text() mehtod. I want to calculate the SUM of this value with some other value that is a number. I am getting a NaN retun now. code is something like this
I have the value in my page like this <p id="typeinfo2">445</p>, value coming dynamically
var oldtotal = parseInt($('#typeInfo2').text(), 10);
var xtra = 75;
var newtotal = oldtotal + xtra;
alert(newtotal) gives me a NaN. I have already tried with - Number(oldtotal) + Number(xtra)
You have a typo. id of p tag is typeinfo2 and not typeInfo2:
var oldtotal = parseInt($('#typeinfo2').text(), 10);
Working Demo
Your spelling mistake
Change Id typeInfo2 to typeinfo2 in your jQuery code.
var oldtotal = parseInt($('#typeinfo2').text(), 10);
var oldtotal = parseInt($('#typeinfo2').text(), 10);
var xtra = 75;
var newtotal = oldtotal + xtra;
alert(newtotal);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p id="typeinfo2">445</p>
I want to be able to take the value from the calcOrderTotal input and then divide it and display the divided output in another input (for example, to show the Order Total price, and then what the order total 36 monthly lease price would be). I sort of attempted to do it with the "calc36Month" function, but I know it's not right.
function calcOrderTotal() {
var orderTotal = 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var serverPrice = $('.server-radio:checked').val() || 0;
var equipmentPrice = $('.equipment-radio:checked').val() || 0;
var underTotal = $("#under-box").val() || 0;
var orderTotal = parseFloat(CleanNumber(productSubtotal)) + parseFloat(CleanNumber(serverPrice)) + parseFloat(CleanNumber(equipmentPrice));
$("#order-total").val(CommaFormatted(orderTotal));
$("#fc-price").attr("value", orderTotal);
}
The calcOrderTotal function is then redirected to this HTML input and displays a dollar value (this does work):
<input type="text" class="total-box" value="$0" id="order-total" disabled="disabled" name="order-total"></input>
I want to be able to take the OrderTotal dollar value and divide it by 36 months and input the 36 month lease value into another input. Here is an example of what I'm looking for (I know this does not work):
function calc36Month() {
var 36Month = 0;
var orderTotal = $("#order-total").val() || 0;
var 36Month = parseFloat(CleanNumber(orderTotal)) / 36;
$("#36-monthly-total").val(CommaFormatted(36Month));
$("#fc-price").attr("value", 36Month);
}
How can I do this?
Here ya go:
function calcOrderTotal() {
var orderTotal = 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var serverPrice = $('.server-radio:checked').val() || 0;
var equipmentPrice = $('.equipment-radio:checked').val() || 0;
var underTotal = $("#under-box").val() || 0;
var orderTotal = parseFloat(CleanNumber(productSubtotal)) + parseFloat(CleanNumber(serverPrice)) + parseFloat(CleanNumber(equipmentPrice));
$("#order-total").val(CommaFormatted(orderTotal));
$("#fc-price").attr("value", orderTotal);
if (orderTotal > 0) {
calcMonthly(orderTotal);
}
}
EDIT: Edited per request.
function calcMonthly(total) {
var pmt1 = total / 36;
var pmt2 = total / 24;
var pmt3 = total / 12;
$("#monthly-36").val(CommaFormatted(pmt1));
$("#monthly-24").val(CommaFormatted(pmt2));
$("#monthly-12").val(CommaFormatted(pmt3));
//$("#fc-price").attr("value", pmt1); // what is the purpose of this?
}
Avoid using numeric digits as variable names, element ID's or CSS classes, or beginning any of the aforementioned references with a number. Begin all variable names, ID's and classes with a letter.