Reputation: 55
I need to show the output (sum, difference, product, quotient) of the 2 numbers in the span below the form. I have tried many variations but cannot get the sum and etc to show at all. Please help I'm a Javascript noob!!! Thanks!
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 />
Upvotes: 0
Views: 143
Reputation: 239523
To assign value to a span tag, we need to use innerHTML
property, not value
.
document.getElementById('sum').innerHTML = sum;
document.getElementById('difference').innerHTML = difference;
document.getElementById('product').innerHTML = product;
document.getElementById('quotient').innerHTML = quotient;
And Change
<form action="" method="post" id="theForm">
to
<form action="" method="post" id="theForm" onsubmit="return calculate()">
You just have to invoke the calculate
function on form's submission.
Upvotes: 1