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.
>Solution :
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
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="convertToFahrenheit" type="text" placeholder="Fahrenheit" oninput="calculate()"></input>
<input id="convertToCelsius" type="text" placeholder="Celsius"></input>
<script>
function calculate() {
let fahrenheit = document.getElementById("convertToFahrenheit").value;
if (fahrenheit !== "") {
document.getElementById("convertToCelsius").value = Math.round((parseFloat(fahrenheit) - 32) * 5 / 9);
} else {
document.getElementById("convertToCelsius").value = "";
}
}
</script>
</body>
</html>
If any problem reply me.