简体   繁体   中英

How do i get HTML form value to use in a javascript function?

So im trying to build a temperature converter that uses a single number input form that when submitted, converts to farenheit/celsius but since im a beginner in javascript, i dont know much and i've tried searching but the questions didnt relate to me.

heres my code:

 function toCelsius(f) { return (f - 32) * (5 / 9); }; function toFarenheit(c) { return (c * 9 / 5) + 32; }; var numInput = document.getElementById("temp-num").value; var type = "celsius"; //test var result = toFarenheit(2); document.getElementById("resultz").innerHTML = numInput + " in" + type + " is " + result;
 <form id="form1"> <input type="number" name="temperature" placeholder="50" id="temp-num" /> <input type="reset" class="bn3637 bn36" /> <div class="buttons"> <label for="test"> <a href="#" onclick="document.getElementById('form1').submit();"> <span></span> <span></span> <span></span> <span></span> <p style="font-size: 15px">TO FAHRENHEIT</p> </a> </label> <a href="#" onclick="document.getElementById('form1').submit();"> <span></span> <span></span> <span></span> <span></span> TO CELSIUS </a> </div> </form> <div class="results"> <div id="result-title"> <h2>Result:</h2> </div> <div class="final-result"> <p id="resultz"></p> </div> </div> <script src="test.js"></script> </body> </html>

You don't need pass the number in the function, you can consult inside the function with document.getElementById("temp-num").value and you can parse value to change string into number

try this:

function toCelsius() {
  let numInput = parseFloat(document.getElementById("temp-num").value);
  return (numInput - 32) * (5 / 9);
};

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