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>
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
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);
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.
form.getElement('ar_essay1_read1_subscore4').bind('change', function() {
calcEssayScore();
}).bind('keyup', function() { $(this).triggerHandler('change'); });
function calcEssayScore()
{
var score1 = form.getElement('ar_essay1_read1_subscore1').val();
var score2 = form.getElement('ar_essay1_read1_subscore2').val();
var score3 = form.getElement('ar_essay1_read1_subscore3').val();
var score4 = form.getElement('ar_essay1_read1_subscore4').val();
var recalc = ((score1 + score2 + score3 + score4) / 4);
form.getElement('sys:app:ar_essay1_read1').val(recalc.toFixed(3));
}
I know this is a total rookie javascript error, but this keeps returning errors. If i put 4 into each field in the form, it's return 1111.000 as the sys:app:ar_essay1_read1 score. How should I be structuring the formula to make it work correctly?
You need to use parseInt(val, 10) or parseFloat(val) to convert the value of each form field as number. Otherwise, you are just doing string manipulation.
I'm trying to have the price show in JavaScript when my button is clicked but it is just showing me my alert. Can anyone tell me where I went wrong? This is my function:
function prompttotalCost() {
var totalCost;
var costPerCD;
var numCDs;
numCDS = prompt("Enter the number of Melanie's CDs you want to buy");
if (numCDS > 0) {
totalCost = totalCost + (costPerCD * numCDs);
alert("totalCost+(costPerCD*numCDs)");
totalCost = 0;
costPerCD = 5;
numCDs = 0;
} else {
alert("0 is NOT a valid purchase quantity. Please press 'OK' and try again");
} // end if
} // end function prompttotalCost
The problem is that numCDs is a string, not a number, because prompt returns a string. You can e.g. use parseInt to convert it to a number:
numCDS = parseInt(prompt("Enter the number of Melanie's CDs you want to buy"));
Next thing: You are not assigning a value to totalCost before using it – that's bad. Either change var totalCost; to var totalCost = 0; or change totalCost = totalCost + (costPerCD * numCDs); to totalCost = (costPerCD * numCDs);.
Also, in your alert invocation, you are putting something that you want to be executed as code into a string. Change
alert("totalCost+(costPerCD*numCDs)");
to something like this:
alert("totalCost is "+totalCost);