Search code examples
javascripthtmlbuttoninputparsefloat

result of input box times 2 appears in window not div


I'm trying to get a text box where you can enter a number and then you click the button and it will multiply it by two and display that result in theDiv. Right now, it opens a new page for the result, and displays the entered number, not the number times two. What am I doing wrong? Beginner here, please be gentle! Thank you!!

<html>
<script>
function doubleit()
{
var theNumber=document.write(parseFloat(document.getElementById('theInput').value));
var doubleNumber =document.getElementById('theNumber')*2;
document.getElementById('theDiv').innerHTML(document.getElementById('doubleNumber'))
}
</script>
<body>
<p>Value: <input type="text" id="theInput" value="" size=10>
<input type="button" id="theButton" value="click me!" onclick="doubleit()"></p>
<div id="theDiv"></div>
</body>
</html>

Solution

  • It's the call to document.write that is replacing the page. Remove it:

    var theNumber=parseFloat(document.getElementById('theInput').value);
    

    When you want the value of a variable, you shouldn't use document.getElementById:

    var doubleNumber = theNumber * 2;
    

    innerHTML is a property, not a method:

    document.getElementById('theDiv').innerHTML = doubleNumber;