Pregunta

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>
¿Fue útil?

Solución

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;

Otros consejos

var doubleNumber = Number(theNumber, 10)*2;
document.getElementById('theDiv').innerHTML(doubleNumber);

Something like this

function doubleit()
{
var theNumber=parseFloat(document.getElementById('theInput').value) * 2;
document.getElementById('theDiv').innerHTML = theNumber;
}

Try This Solution :

Use the id of your button to call the function to calculate result.

theButton.onclick = function doubleit()
{
    //Simply get the number from user and parse it as float.
    var theNumber=parseFloat(document.getElementById('theInput').value);
    //Multiply it with 2
    var doubleNumber =theNumber*2;

    //Display the result in another div
    document.getElementById('theDiv').innerHTML = doubleNumber;
}

Demo

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top