Question

I am relatively new to javascript and I created a function to multiply two numbers together, but document.write replaces the whole page with the answer. I know this is what document.write is supposed to do, but just wanted an alternative. Remember, I am new to the language, so if it's possible, try to explain the answer. Thanks!

<script language="javascript">
    function calculate(){
        var number1= document.getElementById("num1"); 
        var number2= document.getElementById("num2");
        var answer=number1.value * number2.value;
        document.write(answer);
    }
</script>
Was it helpful?

Solution

You already know how to use document.getElementById() to retrieve the values of inputs on your page. So do something similar to update an element that holds the answer:

<div id="answer"></div>

...and then:

document.getElementById("answer").innerHTML = answer;

Simle demo: http://jsfiddle.net/V5R5h/1/

OTHER TIPS

If you add an empty element like <span id="fillme"></span> to the document you can use this with var fillme = document.getElementById("fillme"); and then later assign content to fillme with fillme.innerHTML = answer;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top