I’m trying to create a form based calculator for a business equation which works out break-even return on ad spend.
The fucntion works, I’ve testred it through the console on Chrome. But this is ony when I set the variables to numbers, I’m struggling to use the data from the form to work it out.
I don’t know if using a form is right for this. The part I can’t figure out is linking the HTML form data to the JS variables.
JavaScript
x
20
20
1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<meta charset="UTF-8">
5
<meta http-equiv="X-UA-Compatible" content="IE=edge">
6
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7
<link rel="stylesheet" href="style.css">
8
<title></title>
9
</head>
10
<body>
11
<form id="main">
12
<label for="rprice">Retail Price: </label>
13
<input type="number" id="rprice"><br><br>
14
<label for="cogoods">Cost of Goods: </label>
15
<input type="number" id="cogoods"><br><br>
16
</form>
17
</body>
18
</html>
19
20
JavaScript
1
8
1
let retailPrice = document.getElementById("rprice")
2
let costOfGoods = document.getElementById("cogoods")
3
let difference = retailPrice - costOfGoods
4
5
function calculate () {
6
return (retailPrice / difference)
7
};
8
Advertisement
Answer
Take in consideration:
- to get the value of any input use attribute
.value
JavaScript
1
5
1
function calculate (){
2
let difference = retailPrice.value - costOfGoods.value
3
return retailPrice.value / difference
4
};
5
Add submit
input to fire the function calculate()
JavaScript
1
2
1
<input type="submit" value="calculate">
2
- to get the returned value from a function you have to call it.
JavaScript
1
6
1
let form = document.getElementById("main");
2
form.addEventListener("submit",function(event){
3
event.preventDefault();
4
console.log(calculate());
5
});
6
Note: event.preventDefault()
prevent the form from reloading.
JavaScript
1
12
12
1
let retailPrice = document.getElementById("rprice");
2
let costOfGoods = document.getElementById("cogoods");
3
let form = document.getElementById("main");
4
form.addEventListener("submit",function(event){
5
event.preventDefault();
6
console.log(calculate());
7
document.getElementById("display").innerHTML = calculate();
8
});
9
function calculate (){
10
let difference = retailPrice.value - costOfGoods.value
11
return retailPrice.value / difference
12
};
JavaScript
1
8
1
<form id="main">
2
<label for="rprice">Retail Price: </label>
3
<input type="number" id="rprice" ><br><br>
4
<label for="cogoods">Cost of Goods: </label>
5
<input type="number" id="cogoods" ><br><br>
6
<input type="submit" value="calculate">
7
</form>
8
<div id="display"></div>