I'm very much a beginner to JavaScript and am trying to complete a simple bill splitting exercise. Into a HTML form you input the price of a meal, how many people are paying, and how much of a tip you want to leave, and then it is supposed to give the price that each person should pay. When I put in values of say Price: 100, Tip:0, Number of people: 2, I expect it to give a value of 50, but it gives 500. I believe this is because it is recognizing the inputs as strings as opposed to integers.
I have attempted converting the strings using Number(), and parseInt(), but neither of these seem to have worked, instead giving errors that the values are then unidentified.
const price = document.querySelector("#price");
const numPeople = document.querySelector("#number-people");
const tip = document.querySelector("#tip");
const errorMsg = document.querySelector("#error-msg");
const resultDisplay = document.querySelector("#result");
form.addEventListener("submit", onSubmit);
function onSubmit(e) {
e.preventDefault();
console.log("BUTTON CLICKED"); // CONFIRM BUTTON PRESSED
if(price.value === "" || numPeople.value === "" || tip.value === "") { // SIMPLE VALIDATION
errorMsg.innerHTML = "ENTER ALL FIELDS"; // ENTER HTML INTO error-msg DIV
conole.log("NOT ALL FIELS WERE ENTERED"); // SEND ERROR TO LOG
} else {
console.log("SUCCESS"); // SEND CONFIRMATION TO LOG
console.log(`Price is ${price.value}, number of people is ${numPeople.value} and tip is ${tip.value}`); // SEND VALUES ENTERED TO LOG
const result = (price.value + tip.value) / numPeople.value; // COMPLETE CALCULATION
console.log(result); // SEND THE RESULT TO THE LOG
}
}
I expect the output of (100 + 0) / 2 to be 50, but it is 500.
When using parseInt() and Number() I did:
const result = (parseInt(price.value) + parseInt(tip.value)) / parseInt(numPeople.value);
and Number() respectively.
Sorry if this is a simple question, any help would would be appreciated.