需要帮助使用Javascript获取输出

时间:2013-10-20 02:37:37

标签: javascript

我需要在表格下方的范围内显示2个数字的输出(总和,差异,乘积,商)。我已经尝试了很多变化,但无法得到总和等等。请帮助我是一个Javascript noob!谢谢!

 function calculate() {
'use strict';

// Read the first text box and convert to a float
var input = document.getElementById('number1').value;
var number1 = parseInt(input);


var input = document.getElementById('number2').value;
var number2 = parseInt(input);


// Calculations 
sum = number1 + number2;
difference = number1 - number2;
product = number1 * number2;
quotient = number1 / number2;

// Display the results in relevant spans
document.getElementById('sum').value = sum;
document.getElementById('difference').value = difference;
document.getElementById('product').value = product;
document.getElementById('quotient').value = quotient;


return false;

} 


function init() {
'use strict';
    document.getElementById('theForm').onsubmit = calculate;
} 
window.onload = init;

HTML

<form action="" method="post" id="theForm">
    <fieldset>
        <div><label for="number1">Number 1</label>
            <input type="text" name="number1" id="number1" required>
        </div>
        <div><label for="number2">Number 2</label>
            <input type="text" name="number2" id="number2" required>
        </div>
        <br />
        <div><input type="submit" value="Calculate"></div>
    </fieldset>
</form>

<span id="sum"></span><br />
<span id="difference"></span><br /> 
<span id="product"></span><br />
<span id="quotient"></span><br />

1 个答案:

答案 0 :(得分:1)

要为span标记指定值,我们需要使用innerHTML属性,而不是value

document.getElementById('sum').innerHTML = sum;
document.getElementById('difference').innerHTML = difference;
document.getElementById('product').innerHTML = product;
document.getElementById('quotient').innerHTML = quotient;

并改变

<form action="" method="post" id="theForm">

<form action="" method="post" id="theForm" onsubmit="return calculate()">

您只需要在表单提交时调用calculate函数。