Nan proplem in JS - javascript

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

Related

No clue what's wrong with my code [duplicate]

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);

Operator '+' always concats the value instead of adding

I have started learning Javascript recently and I am trying to create a script used to calculate a set of user input numbers. I use a function to give a prompt to the user and get the value from the user. Then I use another function to take the prompt input and add it to my own value. But the result is always a set of continuous values. My code is the following one, please help.
<body>
<p>
Click below to calculate a value.
</p>
<button onclick='myfunc()'>Calculate</button>
<p id='demo'></p>
<script type='text/javascript'>
function getvalue() {
var foo = prompt('Enter a number');
return(foo);
}
function myfunc() {
var a = getvalue();
var x = a + 2;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
Use parseInt()
https://www.w3schools.com/jsref/jsref_parseint.asp
Either you can use it inside your function or outside like following.
function getvalue() {
var foo = prompt('Enter a number');
parseInt(foo); //Parse string to integer
}
OR
function myfunc() {
var a = parseInt(getvalue()); //Parse string to integer
var x = a + 2;
document.getElementById("demo").innerHTML = x;
}
Dont forget to do validation (to make sure it's an integer) of the prompt output in your program !
All inputs from prompt are treated as a string. You need to specify the var type to be a number (it can be an integer - int - or decimal - double or float). To parse the value just use parseInt, parseDouble, parseFloat.
Difference between double and float is the decimal accuracy.
function getvalue() {
var foo = prompt('Enter a number');
return parseInt(foo); // also try parseDouble for decimal values
}
function myfunc() {
var a = getvalue();
var x = a + 2;
document.getElementById("demo").innerHTML = x;
}
<button onclick="myfunc()">Test</button>
<br/>
<p>
The Value is: <span id="demo"></span>
</p>
You can convert your string into a number with the + operator :
function getvalue() {
// v Here is where the magic is taking place
var foo = +prompt('Enter a number');
return(foo);
}
function myfunc() {
var a = getvalue();
var x = a + 2;
document.getElementById("demo").innerHTML = x;
}

How to subtract values from text field to apply discount from total?

Here is my code
What i am trying to do is to subtract from total value to give discount.
<script type="text/javascript">
function gettotal(){
var arr = document.getElementsByName('feetype');
var discount = parseInt(document.getElementsByName('discount').value);
var tot=0;
for(var i=0;i<arr.length;i++){
if( parseFloat(arr[i].value))
tot += parseFloat(arr[i].value);
tot = tot - discount;
}
document.getElementById('recieveable').value = tot;
}
</script>
enter image description here
Well this is wrong var discount = parseInt(document.getElementsByName('discount').value);
document.getElementsByName returns array of element but here you are expecting a single element. Therefore you should user document.getElementById instead OR you can use what you are using with array index.
Change it to
var discount = parseInt(document.getElementById('discount').value);
OR
var discount = parseInt(document.getElementsByName('discount')[0].value);
if you've only one discount field.

How to calculate point values in javascript?

I have written code to calculate the values like integer values.
function add_number(inp) {
var tr = inp.parentNode.parentNode;
var first_number = parseInt(tr.querySelector('[data-id="qty"]').value);
var second_number = parseInt(tr.querySelector('[data-id="amtper"]').value);
var result = first_number * second_number;
tr.querySelector('[data-id="total"]').value = result ? result : '';
}
By the above code U am able to calculate only round values, if I calculate the values 10.60*10 = 106, (the value should be displayed). But I am getting 100.
How to calculate point values?
if I calculate the values 10.60*10 = 106, (the value should be
displayed). But I am getting 100
Because when you do parseInt, it returns an Intger without any decimal value.
Use parseFloat instead, Replace
var first_number = parseInt(tr.querySelector('[data-id="qty"]').value);
var second_number = parseInt(tr.querySelector('[data-id="amtper"]').value);
with
var first_number = parseFloat(tr.querySelector('[data-id="qty"]').value);
var second_number = parseFloat(tr.querySelector('[data-id="amtper"]').value);
parseInt() parses only integer values without decimal value.
Use parseFloat() instead.
var first_number = parseFloat(tr.querySelector('[data-id="qty"]').value);
var second_number = parseFloat(tr.querySelector('[data-id="amtper"]').value);
Use parseFloat? See this:
function add_number(inp) {
var tr = inp.parentNode.parentNode;
var first_number = parseFloat(tr.querySelector('[data-id="qty"]').value);
var second_number = parseFloat(tr.querySelector('[data-id="amtper"]').value);
var result = first_number * second_number;
tr.querySelector('[data-id="total"]').value = result ? result : '';
}
add_number(document.getElementById("inp"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
QTY: <input data-id="qty" value="100"><br>
AMTPER: <input data-id="amtper" value="1.06">
<div>
<div id="inp"></div>
</div>
<hr>
Total, filled by JS:
<input data-id="total">
</div>
parseInt will convert 10.60 to 10 before the multiplication. You need to use parseFloat instead. In case you expect an integer or a number with fixed number digits after the decimal point, you can use the precision parameter to set it.
function add_number(inp, precision) {
precision = typeof precision !== "number"? 0: precision;
var tr = inp.parentNode.parentNode;
var first_number = parseFloat(tr.querySelector('[data-id="qty"]').value);
var second_number = parseFloat(tr.querySelector('[data-id="amtper"]').value);
var result = (first_number * second_number).toFixed(precision);
tr.querySelector('[data-id="total"]').value = result ? result : '';
}

Jquery Converting a string to Integer

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>

Categories