简体   繁体   中英

How do I get rid of the NaN error when converting temperature with a function in JavaScript?

I have been trying to make a JS Fahrenheit to Celsius converter, and for some reason whenever I input a number and that goes through the function, it spits back out a NaN where the Temperature is supposed to go.

Edit: Added in the "value" after the "ftemp" and "ctemp"

Edit: I deleted the values in the ftemp and ctemp and instead tried to access them in the function itself just like two people answered, and it works fine now.

 function ftoc(ft) { c = ft * (9 / 5) + 32; return c; } function ctof(ct) { f = (c - 32) / (9 / 5); return f; } button1 = document.getElementById("ftempsubmit"); button2 = document.getElementById("ctempsubmit"); fvalue = document.getElementById("ftemp").value; cvalue = document.getElementById("ctemp").value; fpopup = document.getElementById("fpopup"); cpopup = document.getElementById("cpopup"); button1.onclick = function() { cpopup.value = ftoc(fvalue); }; button2.onclick = function() { fpopup.value = ctof(cvalue); };
 <input type="text" id="ftemp" placeholder="Enter F" /> <button id="ftempsubmit">Submit F</button> <br /> <br /> <input id="cpopup" /> <br /> <br /> <input type="text" id="ctemp" placeholder="Enter C" /> <button id="ctempsubmit">Sumbit C</button> <br /> <br /> <input id="fpopup" />

You are not sending the actual value of the inputs but rather the HTML element to your function which will throw NaN

I have also change the type=text to type=number as you will using integer only for conversion .

In your function ctof you are getting argument at ct but you are using c only when doing the calculation which mean it will throw an error of c not defined.

Live Demo:

 function ftoc(ft) { var c = ft * (9 / 5) + 32; return c; } function ctof(ct) { var f = (ct - 32) / (9 / 5); return f; } button1 = document.getElementById("ftempsubmit"); button2 = document.getElementById("ctempsubmit"); fvalue = document.getElementById("ftemp"); cvalue = document.getElementById("ctemp"); fpopup = document.getElementById("fpopup"); cpopup = document.getElementById("cpopup"); button1.onclick = function() { cpopup.value = ftoc(+fvalue.value); }; button2.onclick = function() { fpopup.value = ctof(+cvalue.value); };
 <!DOCTYPE html> <html> <head></head> <body> <input type="number" id="ftemp" placeholder="Enter F" /> <button id="ftempsubmit">Submit F</button> <br /> <br /> <input id="cpopup" /> <br /> <br /> <input type="number" id="ctemp" placeholder="Enter C" /> <button id="ctempsubmit">Sumbit C</button> <br /> <br /> <input id="fpopup" /> <br /> <br /> <script> </script> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM