Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript onclick in textbox always returns me value 0 for my first click into the box

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading