Skip to content
Advertisement

I’m trying to make a form based calculatorfor a business equation

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.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title></title>
</head>
<body>
        <form id="main">
            <label for="rprice">Retail Price: </label>
            <input type="number" id="rprice"><br><br>
            <label for="cogoods">Cost of Goods: </label>
            <input type="number" id="cogoods"><br><br>        
        </form>
</body>
</html>

let retailPrice = document.getElementById("rprice")
let costOfGoods = document.getElementById("cogoods")
let difference = retailPrice - costOfGoods

    function calculate () {
        return (retailPrice / difference)
     };

Advertisement

Answer

Take in consideration:

  1. to get the value of any input use attribute .value
function calculate (){
    let difference = retailPrice.value - costOfGoods.value
    return retailPrice.value / difference 
 };

Add submit input to fire the function calculate()

<input type="submit" value="calculate">
  1. to get the returned value from a function you have to call it.
let form = document.getElementById("main");
form.addEventListener("submit",function(event){
    event.preventDefault();
    console.log(calculate());
});

Note: event.preventDefault() prevent the form from reloading.

let retailPrice = document.getElementById("rprice");
let costOfGoods = document.getElementById("cogoods");
let form = document.getElementById("main");
form.addEventListener("submit",function(event){
    event.preventDefault();
    console.log(calculate());
    document.getElementById("display").innerHTML = calculate();
});
function calculate (){
    let difference = retailPrice.value - costOfGoods.value
    return retailPrice.value / difference 
 };
<form id="main">
    <label for="rprice">Retail Price: </label>
    <input type="number" id="rprice" ><br><br>
    <label for="cogoods">Cost of Goods: </label>
    <input type="number" id="cogoods" ><br><br>        
    <input type="submit" value="calculate">
</form>
<div id="display"></div>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement