Why is my number coming up as 0? [duplicate] - javascript

This question already has answers here:
How do I get the value of text input field using JavaScript?
(16 answers)
Closed 6 years ago.
I am trying to make a calculator that calculates the amount of calories that have been burned in a certain amount of time, but whenever I run it, I get 0 as the output. I have tried setting the calorieCountOut variable to an arbitrary number, and then it works fine, but every time I run it with this code here, I get 0. Here is my code:
const AGECONST = 0.2017;
const WEIGHTCONST = 0.09036;
const HRCONST = 0.6309;
const SUBTRACTCONST = 55.0969;
const TIMECONST = 4.184;
//var gender = document.getElementById("gender").innerHTML;
var gender = "male";
var weight = document.getElementById("weight");
var age = document.getElementById("age");
var time = document.getElementById("time");
var hr = 140;//dummy number
function calculate(){
if (gender = "male"){
var calorieCount = ((age * AGECONST) - (weight * WEIGHTCONST) + (hr * HRCONST) - SUBTRACTCONST) * time / TIMECONST;
}
//else if (gender = "female"){
//}
var calorieCountOut = calorieCount.toString();
document.getElementById("output").innerHTML = calorieCountOut;
}

Try getElementById('myId').value for the value inside the control instead of the control itself as an object.
Right now you assign a html object to a variable, but what you want (i assume) is the number stored in that html object.

Related

How do I make this function a number? [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed last year.
I'm learning JavaScript and I wanted to accept user input and add a number to it ,but instead of outputting 12+12 = 24 it's outputting 12+ 12 = 1212.
document.getElementById("mybutton").onclick = function(){
var myAge = document.getElementById("mytext").value + 12;
document.getElementById("value").innerHTML = myAge;
}
I tried doing:
myName = Number(myName)
but it didn't work
In this case use a function parseInt()
example:
document.getElementById("mybutton").onclick = function(){
var myAge = parseInt(document.getElementById("mytext").value) + 12;
document.getElementById("value").innerHTML = myAge;
}

set input values in array and randomize content to display

I can't seem to find any solutions.
I want to create a form that collects 4 nicknames after submit a form and then displays them all randomly in html code using javascript
My 4 input values are now in an array.
I have to display them randomly in two different teams.
I'm trying to get a random index, and as long as it's different from the ones already assigned to avoid one person being on both teams.
This code works, but sometimes, one player is assigned to 2 teams. Then, the randomizer doesn't work... Do you have an idea ?
function getRandomNumber(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function getData() {
let joueur1 = document.querySelector("#player1").value;
let joueur2 = document.querySelector("#player2").value;
let joueur3 = document.querySelector("#player3").value;
let joueur4 = document.querySelector("#player4").value;
playerList.push(player1.value);
playerList.push(player2.value);
playerList.push(player3.value);
playerList.push(player4.value);
randomNumber1 = getRandomNumber(playerList.length);
last1 += randomNumber1;
random1.textContent = playerList[randomNumber1];
do {
randomNumber2 = getRandomNumber(playerList.length);
} while (randomNumber2 == last1 && last4 && last3);
last2 += randomNumber2
random2.textContent = playerList[randomNumber2];
do {
randomNumber3 = getRandomNumber(playerList.length);
} while (randomNumber3 == last1 && last2 && last4);
last3 += randomNumber3
random3.textContent = playerList[randomNumber3];
do {
randomNumber4 = getRandomNumber(playerList.length);
}while (randomNumber4 == last1 && last2 && last3)
random4.textContent = playerList[randomNumber4];
last4 += randomNumber4
}
Thanks for your help !
Here is a simple way of getting a random item from your array
Here you add your items into array
let joueur1 = document.querySelector("#player1").value;
let joueur2 = document.querySelector("#player2").value;
let joueur3 = document.querySelector("#player3").value;
let joueur4 = document.querySelector("#player4").value;
let playerList=[];
playerList.push(joueur1);
playerList.push(joueur2);
playerList.push(joueur3);
playerList.push(joueur4);
Then, Here is how you can get randomized content
let randomPlayer = playerList[Math.floor(Math.random() * playerList.length)];
Math.random() will never be 1. The largest index is always one less than the length of the array

interchanging and manipulating two form input values

I've created a calculator that requires a value in either months or years in order to perform a calculation. The calculator works with one exception: It is required that the two input fields update based on the value of each other. here's an example of the behavior I am attempting to recreate:
https://www.bankrate.com/calculators/mortgages/loan-calculator.aspx
I apologize in advance if the following example reads poorly, but here it goes:
If a user enters 72 'months', the 'years' input will divide months by 12 and display the result. After doing a little tooling around, I found that using [a, b] = [b*12, a/12] gets me halfway there. The problem I'm running into is that once values have been entered, the value of the most recently updated input is updated with the previous value (including the calculation). For example, User enters 60 months > years is populated with the value of 5 > user changes months to a value of 72 > years is populated with a value of 6 > months is automatically populated with a value of 60 (years remains at a value of 6)
Here's the JS:
const loan = () => {
let principal = document.getElementById('principal')
let interestRate = document.getElementById('interestRate')
let terms = document.getElementById('terms')
let termsInYears = document.getElementById('termsInYears')
let payment = document.getElementById('payment')
let total = document.getElementById('total')
let totalInterest = document.getElementById('totalInterest')
let closingCosts = document.getElementById('closingCosts')
let netAfterFees = document.getElementById('netAfterFees')
let totalFeesAndInterest = document.getElementById('totalFeesAndInterest')
let trueCost = document.getElementById('trueCost')
let amount = parseFloat(principal.value)
let interest = parseFloat(interestRate.value) / 100 / 12
let payments = parseFloat(terms.value)
let fees = parseFloat(closingCosts.value)
if(!fees) {
closingCosts.value = 0
}
[terms.value, termsInYears.value] = [termsInYears.value*12, terms.value/12]
let x = Math.pow(1 + interest, payments)
let monthly = (amount * x * interest) / (x-1)
let totalPay = (monthly * payments)
if (isFinite(monthly) && payment) {
payment.innerHTML = monthly.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
netAfterFees.innerHTML = (amount - fees).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
total.innerHTML = (totalPay).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
totalInterest.innerHTML = ((monthly * payments) - amount).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
totalFeesAndInterest.innerHTML = (totalPay - amount + fees).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
trueCost.innerHTML = (((totalPay - amount + fees) / amount)*100).toFixed(2)
} else {
payment.innerHTML = '0'
netAfterFees.innerHTML = '0'
total.innerHTML = '0'
totalInterest.innerHTML = '0'
totalFeesAndInterest.innerHTML = '0'
trueCost.innerHTML = '0'
}
}
I can't speak on the quality of the working calculator given my experience level. However, it does work. I'm just having one heck of a time getting past this [likely silly] input exchange.
Any help would be greatly appreciated!
I ended up solving this issue using querySelector and then adding an event listener for each input:
document.querySelector('#terms').addEventListener('input', (e) => {
termsInYears.value = e.target.value / 12
})
document.querySelector('#termsInYears').addEventListener('input', (e) => {
terms.value = e.target.value * 12
})

How to check if a generated number already exists

This code below creates a random costumer number and prints it out with a simple console log, but one feature is missing: It should check if the same costumer number/ID has already been generated before. If so, it should walk through the process again, so a new random number is generated which then is unique. How can I do that with this code? As a programming newbie I unfortunately have NO clue how I could do that. Maybe a while loop and storing the generated number in a variable? Would be totally awesome if you can provide the code, combined with mine or build in the duplicate-checking feature.
function generateCostumerNum() {
// generating a random 8-digit number with numbers from 1 to 9
var zeroToNine = "";
for (counter = 0; counter <= 7; counter++) {
var randomNumber = Math.floor(Math.random() * 9) + 1;
zeroToNine += randomNumber;
}
// calculating the cross-sum of the generated number above
var numberforCrossSum = zeroToNine,
crossSum = 0;
while (numberforCrossSum) {
crossSum += numberforCrossSum % 10;
numberforCrossSum = Math.floor(numberforCrossSum / 10);
}
// building together the final costumer ID string.
var finalCostumerNum = "ID" + zeroToNine + crossSum;
console.log(finalCostumerNum);
};
generateCostumerNum();
You can use a simple while loop that runs as long as the generated number has already been generated:
var already_generated_nums = []; // an array of the numbers already generated
//...
var new_num = generateCostumerNum();
while (already_generated_nums.includes(new_num)) {
new_num = generateCostumerNum();
}
already_generated_nums.push(new_num);

JavaScript is concatenating instead of adding [duplicate]

This question already has answers here:
Javascript concatenating numbers, not adding up
(3 answers)
Closed 5 years ago.
I am using these in my code:
alert(mult); //1.114
alert(profit); //10
price = (mult * profit) + profit;
alert(price); //11.14 should be 21.14
I also tried price = ((mult*profit) + profit); but got the same result. Instead of doing (1.114*10) + 10; it is doing 1.114*10=11.14. It is not adding the additional 10 at the end.
It works fine for me like this. It doesn't seem that concatenation is an issue, because otherwise the value would be '11.1410'.
var mult = 1.114;
var profit = 10;
var price = (mult*profit) + profit;
alert(price);//11.14 should be 21.14
If the profit variable (or both variables) is a string, the result would be "11.1410".
var mult = 1.114;
var profit = '10';
var price = (mult*profit) + profit;
alert(price);//11.1410
The result seems unaffected if just the mult value is a string.
var mult = '1.114';
var profit = 10;
var price = (mult*profit) + profit;
alert(price);//21.14
The variables are probably strings, use parseFloat to convert them to numbers :
mult = parseFloat(mult);
profit = parseFloat(profit);
price = (mult*profit) + profit
The problem is probably that either mult or profit are of type string and not of type number. This can be fixed by explicitly casting.
You can determine the type of your variables in your browser console (i.e. dev tools) with the typeof keyword like this:
typeof foo
If either of your variables are of type string you can convert them to number with parseFloat:
mult = parseFloat(mult);
I just ran this is in the chrome js console F12 key.
var mult = 1.114, profit = 10;
console.log('mult=', mult);//1.114
console.log('profit=', profit);//10
price = (mult*profit) + profit;
console.log('price=', price);//11.14 should be 21.14
And got these results
mult= 1.114
profit= 10
price= 21.14

Categories

Resources