0

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 />
1
  • 1
    Nearly there! You've asked for the .value attribute of the 4 target divs - thing is, divs don't have a .value attribute. Use innerHTML instead. E.g: document.getElementById('sum').innerHTML = sum; Commented Oct 20, 2013 at 2:40

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

THANK YOU!!! The innerHTML did it! It only works in Firefox though. Do you know why?
If it doesnt work on chrome, open the page and press F12 key and see if it shows any errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.