0

Why the price variable always stores the value of 0? I tried everything

function calc() {
  let fuel = document.getElementById("fuel").value;
  let litres = document.getElementById("litres").value;
  alert("fuel:" + fuel + " litres: " + litres);
  let price;
  switch (fuel) {
    case 1:
      price = (4 * litres);
      break;
    case 2:
      price = (3.5 * litres);
      break;
    default:
      price = 0;
  }
  alert(price);
  document.getElementById("main").innerHTML += "Total: " + price + " $<br>";
}
* {
  font-family: Helvetica;
  margin: 0px;
}

#lbaner,
#lbar {
  background-color: RGB(130, 69, 85);
  color: white;
  width: 30%;
  height: 200px;
  text-align: center;
}

#rbaner,
#rbar {
  background-color: RGB(130, 69, 85);
  color: white;
  width: 70%;
  height: 200px;
  text-align: center;
}

#main,
#footer {
  background-color: RGB(240, 234, 226);
  padding: 120px;
}

table,
td {
  border: solid 1px RGB(130, 69, 85);
  color: RGB(130, 69, 85);
  padding: 10px;
}

a {
  color: RGB(240, 234, 226);
}
<!DOCTYPE html>
<html>

<head>
  <title>Fuel station</title>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="styl3.css">
</head>

<body>
  <!-- <div style="float: left;"></div> -->
  <div id="lbaner" style="float: left;">
    <h1>Fuel station</h1>
  </div>
  <div style="float: left;"></div>
  <div id="rbaner" style="float: left;">
    <a href="stacja.html"><img src="home.png"></a>
    <a href="obliczenia.html"><img src="znak.png"></a>
  </div>
  <div style="clear: both;"></div>
  <div id="main">
    <h3>Calculate cost of fuel</h3>
    <p>Fuel type (1-gasoline,2-diesel)</p>
    <input type="number" id="fuel">
    <p>Litres</p>
    <input type="number" id="litres">
    <br>
    <button onclick="calc()">Calculate</button>
  </div>
  <div id="lbar" style="float: left;"><a href="kwerendy.txt">Download queries</a></div>
  <div id="rbar" style="float: left;"><img src="samochod.png" alt="samochód"></div>
  <div style="clear: both;"></div>
  <div id="footer">
    <p>MY PAGE</p>
  </div>
</body>

</html>
Michael M.
  • 10,486
  • 9
  • 18
  • 34
Odissonis
  • 1
  • 1
  • `.value` is always a string. `1` and `2` are numbers. They will never match. Use `.valueAsNumber`. – Sebastian Simon Nov 08 '22 at 18:13
  • **The problem was caused by taking text from input field. It's not number despite of type="number".** 1. Instead of case 1: I should use case '1': etc. 2. Convert value from inputs to integers like so: fuel = parseInt(fuel) etc. – Odissonis Nov 08 '22 at 18:18

0 Answers0