Bug in anonymous function for loop in JavaScript - javascript

var $ = function(id) {
return document.getElementById(id);
};
// var future_value;
var calculateFV = function (investment, interest, years) {
var future_value = investment;
for (var i = 1; i <= years; i++) {
future_value = future_value + (future_value * interest / 100);
}
future_value = future_value.toFixed(2);
return future_value;
//$("future_value").value = calculateFV(investment, interest, years);
};
var processEntries = function () {
var investment = parseFloat($("investment").value);
var interest = parseFloat($("interest").value);
var years = parseFloat($("years").value);
$("future_value").value = calculateFV(investment, interest, years);
};
window.onload = function () {
$("calculate").onclick = processEntries;
};
I think the problem is with the for loop but I don't know, I've tried everything at this point. Nothing will run, maybe you guys can spot the bug?
<label for="investment">Total Investment:</label>
<input type="text" id="investment">
<span id="investment_error"> </span><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="annual_rate">
<span id="rate_error"> </span><br>
<label for="years">Number of Years:</label>
<input type="text" id="years">
<span id="years_error"> </span><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
Thinking now that it's something to do in my HTML?

Your code should work with one minor correction, $("interest").value should be $("annual_rate").value to work with your HTML:
The only thing I would change is to remove the disabled property on the future_value input. With the diasbled attribute on, the value will not be submitted. You can use readonly to prevent users from modifying the field. However you should double check the calculations on the back end in any case.
var $ = function(id) {
return document.getElementById(id);
};
// var future_value;
var calculateFV = function(investment, interest, years) {
var future_value = investment;
for (var i = 1; i <= years; i++) {
future_value = future_value + (future_value * interest / 100);
}
future_value = future_value.toFixed(2);
return future_value;
//$("future_value").value = calculateFV(investment, interest, years);
};
var processEntries = function() {
var investment = parseFloat($("investment").value);
var interest = parseFloat($("annual_rate").value);
var years = parseFloat($("years").value);
$("future_value").value = calculateFV(investment, interest, years);
};
window.onload = function() {
$("calculate").onclick = processEntries;
};
<label for="investment">Total Investment:</label>
<input type="text" id="investment">
<span id="investment_error"> </span><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="annual_rate">
<span id="rate_error"> </span><br>
<label for="years">Number of Years:</label>
<input type="text" id="years">
<span id="years_error"> </span><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" readonly><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>

Works fine. No problem.
var $ = function(id) {
return document.getElementById(id);
};
//var future_value;
var calculateFV = function(investment, interest, years) {
var future_value = investment;
for (var i = 1; i <= years; i++) {
future_value = future_value + (future_value * interest / 100);
}
future_value = future_value.toFixed(2);
return future_value;
//$("future_value").value = calculateFV(investment, interest, years);
};
var processEntries = function() {
var investment = parseFloat($("investment").value);
var interest = parseFloat($("interest").value);
var years = parseFloat($("years").value);
$("future_value").value = calculateFV(investment, interest, years);
};
window.onload = function() {
$("calculate").onclick = processEntries;
};
investment: <input id="investment" type="text" value="1000"><br/>
interest: <input id="interest" type="text" value="8"><br/>
years: <input id="years" type="text" value="2"><br/>
future_value: <input id="future_value" type="text" value="" disabled><br/>
<input type="button" id="calculate" value="Calculate">

Related

JavaScript array application

I'm trying to create a sample accounting system, the checkbox can be add to the total after it's checked and the input text is the amount of the money.
but my result keep getting zero, I can't figure it out.
Anyone can help me handle this problem?
I've test that the length of total_ary is 0, I think that is the mainly problem
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10, 20, 30];
var i = 0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked) {
amount.push(document.getElementsByName("amount").value); //get amounts of the products
} else {
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < total_ary.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = "$" + total ;
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
You do
document.getElementsByName("amount").value
but getElementsByName returns a collection, not an element.
You do
var total_ary = [];
// ... code that doesn't reference total_ary
for (i = 0; i < total_ary.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
But since the code in between doesn't reference total_ary, the total ends up being 0.
From a selected checkbox, you need to navigate to the associated input:
document.getElementsByName("amount")[i].value
since i is the cb index you're iterating over, the same i in the amount collection will refer to the input you need.
Or, more elegantly, just navigate to the next element in the DOM when a checkbox is checked, and take the number for each product's price from the DOM too. You can also select only the checked checkboxes immediately with a :checked selector, and attach the event listener using addEventListener (instead of an inline handler; inline handlers should be avoided)
document.querySelector('button').addEventListener('click', () => {
let total = 0;
for (const input of document.querySelectorAll('[name=cb]:checked')) {
const price = input.nextSibling.textContent.match(/\d+/)[0];
const amount = input.nextElementSibling.value;
total += price * amount;
}
document.getElementById("result").innerHTML = total + "元";
});
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input><br>
<input type="checkbox" name="cb" checked>$20:<input><br>
<input type="checkbox" name="cb" checked>$30:<input><br>
</fieldset>
<button>Count</button>
<p>Total = <span id="result">
document.getElementsByName() returns a collection of elements. so calling value property will not work there as it does not have such property.
You can hold input elements with amount_inputs variable and iterate over it (in the example below by using spread syntax and Array.reduce())
And with Array.reduce() you can calculate the sum of the prices. There is no need for var amount = [] and var total_ary = [] variables.
Hope this helps
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount_inputs = document.getElementsByName("amount")
var total = 0;
var price = [10, 20, 30];
total = [...input_cb].reduce((total, cb, i) => {
if(cb.checked){
total += (parseInt(amount_inputs[i].value) || 0) * price[i]
// ^^^^^^^^^ This is to avoid NaN multiplication
}
return total
},0);
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
Use Index while retrieving the element from document.getElementsByName("amount");
Use for loop on amount array not on total_ary
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10, 20, 30];
var i = 0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked) {
amount.push(document.getElementsByName("amount")[i].value); //get amounts of the products
} else {
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < amount.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += isNaN(parseInt(total_ary[i])) ? 0 : parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = "$" + total ;
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
You have made a few mistakes:
(1) If you want to keep all the checkboxes checked at initial stage
use checked="true" in place of checked
(2) getElementsByName("amount") returns an array, so you should use the index as well
(3) total_ary length is 0 initially.. therefore, you should run the loop with input_cb. (Here, you can do both the task with a single loop: refer code below)
Refer the code with corrections:
<!DOCTYPE html>
<html>
<head>Order sys
<script>
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total = 0;
var price = [10,20,30];
var i=0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked){
amount.push(parseInt(document.getElementsByName("amount")[i].value)); //get amounts of the products
}
else{
amount.push(0); //If there is no input, add 0 to the array
}
total += parseInt(amount[i] * price[i]) //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
</script>
</head>
<body>
<fieldset>
<input type = "checkbox" name="cb" checked="true">$10:<input type="text" id="amount_milk" name="amount" ><br>
<input type = "checkbox" name="cb" checked="true">$20:<input type="text" id="amount_soymlik" name="amount"><br>
<input type = "checkbox" name="cb" checked="true">$30:<input type="text" id="amount_blacktea" name="amount" ><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
</body>
</html>
You can refactor your code:
Fist use inputs of type number <input type="number" name="amount"> to accept only numbers from your end users
Then, you can work with indexed arrays like [...document.querySelectorAll('input[name="cb"]')] and loop only one time with Array.prototype.reduce() to get the total
Code example:
function Totalamount() {
const inputNumberArr = [...document.querySelectorAll('input[name="cb"]')]
const inputAmountArr = [...document.querySelectorAll('input[name="amount"]')]
const priceArr = [10, 20, 30]
const total = inputNumberArr.reduce((a, c, i) => {
const num = c.checked ? +inputAmountArr[i].value : 0
return a + num * priceArr[i]
}, 0)
document.getElementById('result').innerHTML = '$' + 0
document.getElementById('result').innerHTML = '$' + total
}
<fieldset>
<input type="checkbox" name="cb" checked> $10:
<input type="number" name="amount"><br>
<input type="checkbox" name="cb" checked> $20:
<input type="number" name="amount"><br>
<input type="checkbox" name="cb" checked> $30:
<input type="number" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
Is this what you are looking for?
Errors that I identified.
Making use of document.getElementsByName("amount").value instead of making the respective amount field you were making use of the global selector.
Trying to loop total_ary array instead of amount array.
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amountInput = document.getElementsByName('amount');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10,20,30];
var i=0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked && amountInput[i].value){
amount.push(parseInt(amountInput[i].value)); //get amounts of the products
}
else{
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < amount.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
<fieldset>
<input type = "checkbox" name="cb" checked>$10
<input type="text" id="amount_milk" name="amount" ><br>
<input type = "checkbox" name="cb" checked>$20
<input type="text" id="amount_soymlik" name="amount"><br>
<input type = "checkbox" name="cb" checked>$30
<input type="text" id="amount_blacktea" name="amount" ><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">

jS code is not working, not showing total

I am trying to calculate three values using JS, but the total is not being calculated. it gets values from the form elements and then function calculateTotal() is called onchange. But the total is not being displayed.
*I am new on stackoverflow, please be kind!
I was trying to use method Post on the form, removed it.
Also removed any styling.
function getpkgPriceA() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyA"
var QuantityA = theForm.elements["qtyA"];
if (QuantityA == null || QuantityA === false) {
var totalpkgPriceA = 0;
return totalpkgPriceA;
} else {
var totalpkgPriceA = 5.99 * QuantityA.value;
return totalpkgPriceA;
}
}
function getpkgPriceB() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyB"
var QuantityB = theForm.elements["qtyB"];
if (QuantityB == null || QuantityB === false) {
var totalpkgPriceB = 0;
return totalpkgPriceB;
} else {
var totalpkgPriceB = 12.99 * QuantityB.value;
return totalpkgPriceB;
}
}
function getpkgPriceC() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyC"
var QuantityC = theForm.elements["qtyC"];
if (QuantityC == null || QuantityC === false) {
var totalpkgPriceC = 0;
return totapkgPriceC;
} else {
var totalpkgPriceC = 17.99 * QuantityC.value;
return totalpkgPriceC;
}
}
function calculateTotal() {
var TotalpkgPrice = getpkgPriceA() + getpkgPriceB() + getpkgPriceC() + 2;
//display the result
var divobj = document.getElementById('totalprice');
divobj.style.display = 'block';
divobj.innerHTML = "Your Total: £"
TotalpkgPrice.toFixed(2);
}
function hideTotal() {
var divobj = document.getElementById('totalprice');
divobj.style.display = 'none';
}
<form action="#" id="Mangoform">
<div>
<div>
<div>
<span>Small: 1.3kg</span>
<input type="number" id="qtyA" name="qtyA" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">
</div>
</br>
<div>
<span>Large: 3.3kg</span>
<input type="number" id="qtyB" name="qtyB" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">
</div>
</br>
<div>
<span>Small: 5.0kg</span>
<input type="number" id="qtyC" name="qtyC" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">
</div>
</div>
</div>
<span id="totalprice" name='totalprice'>Your Total:</span>
<div>
<input name="submit" type="submit" value="submit" onclick="calculateTotal()">
</div>
</form>
if value in qtyA=1, qtyB=1 and qtyC=1 and adding 2 then total should be displayed
as 38.97
(5.99*1)+(12.99*1)+(17.99*1)+2=38.97
if qtyA=2, qtyB=2 and qtyC=3 adding 2
(5.99*2)+(12.99*2)+(17.99*3)+2=93.93
Please point out the mistake. Thanks.
There is one extra closing curly bracket in getpkgPriceA function. You just need to remove it and also you need to add + sign while adding strings:
"Your Total: £" + TotalpkgPrice.toFixed(2);
Try this:
function getpkgPriceA(){
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyA"
var QuantityA=theForm.elements["qtyA"];
if(QuantityA==null || QuantityA===false){
var totalpkgPriceA = 0;
return totalpkgPriceA;
}
var totalpkgPriceA = 5.99 * QuantityA.value;
return totalpkgPriceA;
}
function getpkgPriceB(){
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyB"
var QuantityB=theForm.elements["qtyB"];
if(QuantityB==null || QuantityB===false){
var totalpkgPriceB = 0;
return totalpkgPriceB;
}
else{
var totalpkgPriceB = 12.99 * QuantityB.value;
return totalpkgPriceB;
}
}
function getpkgPriceC(){
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyC"
var QuantityC=theForm.elements["qtyC"];
if(QuantityC==null || QuantityC===false){
var totalpkgPriceC = 0;
return totapkgPriceC;
}
else{
var totalpkgPriceC = 17.99 * QuantityC.value;
return totalpkgPriceC;
}
}
function calculateTotal(){
var TotalpkgPrice = getpkgPriceA() + getpkgPriceB() + getpkgPriceC() +2;
//display the result
var divobj = document.getElementById('totalprice');
divobj.style.display='block';
divobj.innerHTML = "Your Total: £" + TotalpkgPrice.toFixed(2) ;
}
function hideTotal(){
var divobj = document.getElementById('totalprice');
divobj.style.display='none';
}
<form action="#" id="Mangoform">
<div >
<div>
<div>
<span>
Small: 1.3kg
</span>
<input type="number" id="qtyA" name="qtyA" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100" >
</div>
</br>
<div>
<span>
Large: 3.3kg
</span>
<input type="number" id="qtyB" name="qtyB" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100" >
</div>
</br>
<div>
<span>
Small: 5.0kg
</span>
<input type="number" id="qtyC" name="qtyC" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100" >
</div>
</div>
</div>
<span id="totalprice" name='totalprice'>
Your Total:
</span>
<div>
<input name="submit" type="submit" value="submit" onclick="calculateTotal()" >
</div>
</form>
function getpkgPriceA() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyA"
var QuantityA = theForm.elements["qtyA"];
if (QuantityA == null || QuantityA === false) {
var totalpkgPriceA = 0;
return totalpkgPriceA;
} else {
var totalpkgPriceA = 5.99 * QuantityA.value;
return totalpkgPriceA;
}
}
function getpkgPriceB() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyB"
var QuantityB = theForm.elements["qtyB"];
if (QuantityB == null || QuantityB === false) {
var totalpkgPriceB = 0;
return totalpkgPriceB;
} else {
var totalpkgPriceB = 12.99 * QuantityB.value;
return totalpkgPriceB;
}
}
function getpkgPriceC() {
//Get a reference to the form id="Mangoform"
var theForm = document.forms["Mangoform"];
//Get a reference to the select id="qtyC"
var QuantityC = theForm.elements["qtyC"];
if (QuantityC == null || QuantityC === false) {
var totalpkgPriceC = 0;
return totapkgPriceC;
} else {
var totalpkgPriceC = 17.99 * QuantityC.value;
return totalpkgPriceC;
}
}
function calculateTotal() {
var TotalpkgPrice = getpkgPriceA() + getpkgPriceB() + getpkgPriceC() + 2;
var divobj = document.getElementById('totalprice');
divobj.style.display = 'block';
divobj.innerHTML = "Your Total: £" + TotalpkgPrice.toFixed(2);
}
function hideTotal() {
var divobj = document.getElementById('totalprice');
divobj.style.display = 'none';
}
<form id="Mangoform">
<div>
<div>
<div>
<span>
Small: 1.3kg
</span>
<input type="number" id="qtyA" name="qtyA" placeholder="Quantity" onchange="calculateTotal();" min="1" max="100">
</div>
</br>
<div>
<span>
Large: 3.3kg
</span>
<input type="number" id="qtyB" name="qtyB" placeholder="Quantity" onchange="calculateTotal();" min="1" max="100">
</div>
</br>
<div>
<span>
Small: 5.0kg
</span>
<input type="number" id="qtyC" name="qtyC" placeholder="Quantity" onchange="calculateTotal();" min="1" max="100">
</div>
</div>
</div>
<span id="totalprice" name='totalprice'>
Your Total:
</span>
<div>
<input name="submit" type="button" value="submit" onclick="calculateTotal();">
</div>
</form>
</body>
</html>
As it was pointed out previously with #Saurabh code. The other reason might be the missing + sign in divobj.innerHTML = "Your Total: £" TotalpkgPrice.toFixed(2) ; where it has to be corrected to divobj.innerHTML = "Your Total: £" + TotalpkgPrice.toFixed(2) ;

Use Javascript to Make Calculator

Good Day - I am Learning Javascript, I am trying to create a Calculator to calculate ampere-turn to magnetize a tool (it's related to my job.) I am trying to use some formulas to calculate this ampere-turn. The code seems fine to me, but it's not working. I put some values in the form, and click button submit, but no result found and i don't know why this happens.
I am sharing my code here for your kind review. and help me to fix this problem.
thank you.
function ampereturn()
{
var inputOD = Number(document.ampereturn.inputod.value);
var inputLen = Number(document.ampereturn.inputlen.value);
var InputID = Number(document.ampereturn.Inputid.value);
var InputTurn = Number(document.ampereturn.Inputturn.value);
var ans;
var ldratio = inputLen/inputOD;
var coilradius = InputID/2;
var toolradius = inputOD/2;
var pi = 3.14;
var xcoil = (coilradius * coilradius) * pi;
var xtool = (toolradius * toolradius) * pi;
var factor = xtool/xcoil;
var text = "Use Intermediate Fill-factor formula:";
if(factor >= 0.5)
{
ans = 35000/(ldratio+2)*Inputturn;
document.getElementById('sum').innerHTML = ans;
}
if(factor <= 0.1)
{
ans = 45000/ldratio*Inputturn;
document.getElementById('sum').innerHTML = ans;
}
else
{
document.getElementById('sum').innerHTML = text;
}
}
<form name="ampereturn">
<div class="w3-half w3-margin-top">
<label>Tool OD:</label>
<input id="inputod" class="w3-input w3-border" type="number" placeholder="Input Tool Outer Dia:">
</div>
<div class="w3-half w3-margin-top">
<label>Tool Lenght:</label>
<input id="inputlen" class="w3-input w3-border" type="number" placeholder="Input Tool Length">
</div>
<div class="w3-half w3-margin-top">
<label>Coil ID:</label>
<input id="Inputid" class="w3-input w3-border" type="number" placeholder="Input Coil Internal Dia:">
</div>
<div class="w3-half w3-margin-top">
<label>Coil Turn:</label>
<input id="Inputturn" class="w3-input w3-border" type="number" placeholder="Input Number of turn in coil:">
</div>
<div class="w3-half w3-margin-top">
<label>Required Ampere:</label>
<p id="sum"></p>
</div>
<button type="button" onclick="ampereturn()">Submit</button>
</form>
<br><hr>
thank you in advance. ....
Change the function name which is same as the form name.
Change Inputturn to InputTurn in the if condition.
Required Code:
function Ampereturn()
{
var inputOD = Number(document.ampereturn.inputod.value);
var inputLen = Number(document.ampereturn.inputlen.value);
var InputID = Number(document.ampereturn.Inputid.value);
var InputTurn = Number(document.ampereturn.Inputturn.value);
var ans;
var ldratio = inputLen/inputOD;
var coilradius = InputID/2;
var toolradius = inputOD/2;
var pi = 3.14;
var xcoil = (coilradius * coilradius) * pi;
var xtool = (toolradius * toolradius) * pi;
var factor = xtool/xcoil;
var text = "Use Intermediate Fill-factor formula:";
if(factor >= 0.5)
{
ans = 35000/(ldratio+2)*InputTurn;
document.getElementById('sum').innerHTML = ans;
}
else if(factor <=0.1)
{
ans = 45000/ldratio*InputTurn;
document.getElementById('sum').innerHTML = ans;
}
else
{
document.getElementById('sum').innerHTML = text;
}
}

onClick works only once

I input the values, and it works ONCE, which is a problem.
I try to change the numbers, and click Enter again, and it does nothing.
The only way it works again is if I use the scroll to up or down the current value.
var fuel = 2.5;
var mpg = 6;
function Hourly() {
var miles = document.getElementById('miles').value;
var brokerPay = document.getElementById('pay').value;
var gallons = miles / 6;
var hours = miles / 55;
var cost = gallons * fuel;
var net = brokerPay - cost
var hourlyPay = net / hours;
var newHeader = document.getElementById('changeMe');
newHeader.innerHTML = hourlyPay;
}
<h1 id="changeMe">Change me Here</h1>
<input type="number" placeholder="miles" id="miles" required/>
<input type="number" placeholder="Broker Pay" id="pay" required/>
<input type="submit" value="Enter" onclick="Hourly()" />

Why does this function's results show up as NaN?

I have this simple piece of code:
var numb1 = document.getElementById("numb1")
var numb2 = document.getElementById("numb2")
var numb3 = document.getElementById("numb3")
var numb4 = document.getElementById("numb4")
var v1 = parseInt(numb1)
var v2 = parseInt(numb2)
var v3 = parseInt(numb3)
var v4 = parseInt(numb4)
var t = parseInt(0)
function myFunction() {
if (numb1.checked == true) {
var t = v1 + t
} else if (numb2.checked == true) {
var t = v2 + t
} else if (numb3.checked == true) {
var t = v3 + t
} else if (numb4.checked == true) {
var t = v4 + t
}
document.getElementById("demo").innerHTML = t
}
<input id="numb1" type="radio" value="10">
<input id="numb2" type="radio" value="50">
<input id="numb3" type="radio" value="80">
<input id="numb4" type="radio" value="120">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
I get that I definitely could have been more efficient when making my variables, but my problem is that even after I use parseInt() to go from string to integer, the end result in demo displays NaN. Is there something wrong with the way I defined the variables, or is it the calculation of the end value?
Because parseInt( elementObject ) doesn't return a valid number.
You wanted to parse the value, with a radix
var v1 = parseInt(numb1.value, 10);
And you have to get those values inside the function, when the value has actually changed.
Also, add some semicolons, they aren't always needed, but it's good practice to add them, and don't redeclare variables
var numb1 = document.getElementById("numb1");
var numb2 = document.getElementById("numb2");
var numb3 = document.getElementById("numb3");
var numb4 = document.getElementById("numb4");
function myFunction() {
var v1 = parseInt(numb1.value, 10);
var v2 = parseInt(numb2.value, 10);
var v3 = parseInt(numb3.value, 10);
var v4 = parseInt(numb4.value, 10);
var t = 0;
if (numb1.checked) {
t = v1 + t;
} else if (numb2.checked) {
t = v2 + t;
} else if (numb3.checked) {
t = v3 + t;
} else if (numb4.checked) {
t = v4 + t;
}
document.getElementById("demo").innerHTML = t
}
<input id="numb1" type="radio" value="10">
<input id="numb2" type="radio" value="50">
<input id="numb3" type="radio" value="80">
<input id="numb4" type="radio" value="120">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
I agree with the answer by adeneo. The issue is that you are parseInting an HTML Input Element.
And you already got the answer.
But I noticed that you use if..else
So, You want only one value to be selected by the user.
So, There is a short method which also help to improve the loading speed and reduce lines of codes.
using forms
function myFunction(){
t=parseInt(document.forms[0]["num"].value);
document.getElementById("demo").innerHTML=t
}
<form>
<input id="numb1" name="num" type="radio" value="10">
<input id="numb2" name="num" type="radio" value="50">
<input id="numb3" name="num" type="radio" value="80">
<input id="numb4" name="num" type="radio" value="120">
<button type="button" onclick="myFunction()">Submit</button>
</form>
<p id="demo"></p>

Categories

Resources