My Javascript tipping calculator is not working

I’m still learning programming and i appreciate any help i can get. Id love to know why this doesnt work. :cold_sweat:

Javascript:
document.getElementById("submit").addEventListener("click", calculate(){
  let itemCost = document.getElementById("itemCost");
  let radio = document.getElementsByName('percent');
  var tipAmount = 0;
  for (var i = 0, length = radio.length; i < length; i++)
  {
    if (radio[i].checked)
    {
    var tipAmount = parseInt(radio[i].value);
    break;
    }
  }
    let tip = itemCost.value * (tipAmount/100);
    document.getElementById('tip').innerHTML = tip;
    let total = parseInt(tip) + parseInt(itemCost.value);
    document.getElementById("total").innerHTML = total;
});

html:
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="C:\\Users\\Brittany\\Documents\\randomProjectsCoding\\tippingWebsite.css">
    <script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
  </head>
  <body>
    <form>
      <h1>Tipping Calculator</h1>
      <h2>What is the cost?</h2>
      <input id="itemCost" type="text"></input>
      <h2>What is your desired tip %?</h2>
      <input type="radio" value="10" name="percent">10%</input><br>
      <input type="radio" value="15" name="percent">15%</input><br>
      <input type="radio" value="20" name="percent">20%</input><br>
      <br>
      <button id="submit" type="button" value="enter"><i class="fas fa-heart"></i> Submit <i class="fas fa-heart"></i></button>
      <h2>Amount to tip is:</h2>
      <h1 id="tip"></h1>
      <h2>Total cost is:</h2>
      <h1 id="total"></h1>
    </form>
    <script type="text/javascript" src="C:\\Users\\Brittany\\Documents\\randomProjectsCoding\\tippingWebsite.js"></script>
  </body>
</html>

hello @alteriris
you should have either made an anonymous callback function using function keyword or arrow syntax like this

document.getElementById("submit").addEventListener("click", (event)=>{
    ...code..
})

or made a separate function calculate function and then specified calculate as addeventlisteners’ callback like this

document.getElementById("submit").addEventListener("click", calculate)

Your next mistake is that you have written document.getElementsByName

It should rather be document.getElementsByClassName

1 Like