Javascript - 从数字字段读取输入,执行计算,输出结果

时间:2018-03-14 17:01:41

标签: javascript

我是javascript的初学者,只是寻求一些帮助来解决这个基本问题。我想从一个字段中取一个华氏温度数字,将其转换为摄氏温度,然后输出结果。按钮点击没有任何结果。

HTML:

    function myFunction() {
    	var t0 = document.getElementById('temp1').value;
	    t0 = (t0-32)*.5556;
	    var t1 = document.getElementById('temp2').value;
	    t1 = (t1-32)*.5556;
	    var t2 = document.getElementById('temp3').value;
	    t2 = (t2-32)*.5556;
	    var t3 = document.getElementById('temp4').value;
	    t3 = (t3-32)*.5556;
	    var t4 = document.getElementById('temp5').value;
	    t4 = (t4-32)*.5556;
	    var text = "Temp 1: " + t0 + "<br>";
    	text += "Temp 2: " + t1 + "<br>";
	    text += "Temp 3: " + t2 + "<br>";
	    text += "Temp 4: " + t3 + "<br>";
	    text += "Temp 5: " + t4 + "<br>";
	    document.getElementByID("output").innerHTML = text;
    }
<div align="center">

<form id="form2" action="/action_page.php">
  <label>Temp 1: </label><input class="field" type="number" id="temp1" 
name="temp1" /><br>
  <label>Temp 2: </label><input class="field" type="number" id="temp2" 
name="temp2" /><br>
  <label>Temp 3: </label><input class="field" type="number" id="temp3" 
name="temp3" /><br>
  <label>Temp 4: </label><input class="field" type="number" id="temp4" 
name="temp4" /><br>
  <label>Temp 5: </label><input class="field" type="number" id="temp5" 
name="temp5" /><br><br>
</form>
<p>Click the button to convert from Farenheit to Celsius</p>
<button onclick="myFunction()">Convert</button>
<p id="output"></p>
</div>

2 个答案:

答案 0 :(得分:2)

除了使用ID修正拼写错误,更改为Id, 我真的相信它只是你编写代码的方式。确保将脚本放在head标记内。这是一个jsfiddle示例,其中加载类型位于head内:https://jsfiddle.net/56eet52k/9/

答案 1 :(得分:0)

 document.getElementByID("output").innerHTML = text;
You have a typo so correct above line to like this
 document.getElementById("output").innerHTML = text;