How can I make the result reset in my temperature convert function?

Viewed 42

I made a basic celsius to fahrenheit converter in HTML and Javascript, but I dont know how I can make the result reset when the user enters a new value in the input. The function does work, but when you enter a new value it adds up to the existing one. Does anyone know how to fix this? This is the HTML Code:

 <h1>Temperature Converter</h1>
    <p>Enter degrees in Celsius</p>
    <input id="input" type="number">
    <p id="result">Result: </p> 
    <button onclick="convert()">Convert</button>

And this is the JavaScript code:

function convert() {
let temp = document.getElementById("input").value;
let result = (temp * 1.8 + 32);
let output = document.getElementById("result");
output.innerHTML += result;
}
1 Answers

The problem is you're concatenating result into the output element. You should use assignment (=) instead of concatenation (+=) like so:

function convert() {
  let temp = document.getElementById("input").value;
  let result = (temp * 1.8 + 32);
  let output = document.getElementById("result");
  output.innerHTML = result;
}
<h1>Temperature Converter</h1>
<p>Enter degrees in Celsius</p>
<input id="input" type="number">
<p id="result">Result: </p>
<button onclick="convert()">Convert</button>

Related