Reputation: 121
Basically, I have made a form which allows you to input 2 numbers, and when you press the 'Add' button, the program writes the answer onto the screen, the only thing is when the answer is written, it appears on a separate page. How do I get it to write to the same page, below is the HTML code:
<form type="twoNum" method="get">
<input type="float" placeholder="Enter first number here..." name="num1" id="n1"/>
<input type="float" placeholder="Enter second number here..." name="num2" id="n2"/>
<input type="button" value="Add" name="sndfunct" onClick="twoNum(this.form);"/>
</form>
Below is the Javascript code:
function twoNum(form)
{
var num1 = form.num1.value;
var num2 = form.num2.value;
var intNum1 = parseFloat(num1);
var intNum2 = parseFloat(num2);
document.writeln(intNum1 + intNum2);
}
Upvotes: 1
Views: 4503
Reputation: 11
You can write <p id="answer"></p>
in the form. Then create var answer=intNum1 + intNum2
and after that instead document.writeln(intNum1 + intNum2)
write document.getElementById("answer").innerHTML=answer
!
Upvotes: 1
Reputation: 6650
Please note that using document.write()
is considered bad practice. E.g. see the warning on the W3C web site.
Furthermore, you can’t use it to edit a closed document. document.write()
can only be used while the document is being loaded.
In order to do what you want, you should have a <span id="foo"></span>
somewhere in your document, and then do:
document.getElementById("foo").textContent = intNum1 + intNum2;
This will insert your number inside your span element. Actually, it replaces the content of the (previously empty) span element.
Edit: Of course, it can be any kind of element. I used a span element just for the example.
Upvotes: 2