I’m new to JavaScript and just learning the fundamentals. Wanted to build a Fahrenheit to Celsius vice versa calculator. I ran into the issue, that every time I first click into the textbox, before I even type in a value, it automatically recognizes a value "0" and converts 0 into Celsius. I want that the calculation process only starts when numbers with the keyboard are typed in. Is there maybe anyway how to ignore clicks or just to address the input of the keyboard so that it doesn’t calculate the 0.
function calculate(fahrenheit){
fahrenheit = document.getElementById("convertToFahrenheit").value;
document.getElementById("convertToCelsius").value = Math.round((fahrenheit -32) * 5 / 9);
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id= "convertToFahrenheit" type="text" placeholder="Fahrenheit" onclick="calculate()"></input>
<input id="convertToCelsius" type="text" placeholder="Celsius" onclick=""></input>
</body>
</html>
I really have no clue how to fix that, as I am a beginner.
2
Answers
The behavior you’re experiencing is due to the fact that you’ve attached the calculate() function to the click event of the input field. This means that the function will be triggered whenever the input field is clicked, even if no value has been entered yet. To achieve the behavior you’re looking for (calculate only when numbers are typed in), you can use the input event instead of the click event. Try this code
If any problem reply me.
Problem is you are using an
onclick
to call your function so everytime you click on the input, it will call the function despite the fact that you didn’t have the chance to type anything yet.You should avoid using
onclick
on the HTML and make use ofaddEventListener
instead