Reputation: 321
function result()
{
var a, b, c;
a = 10;
b = 20;
c = a+b;
document.write("The result of a+b is" + c);
}
<input type="button" value="Result" onclick=result();>
I'm new to JavaScript, and I'm learning step by step. I tried above example and it's working fine but after click on button result is not showing on same window.
Should I use innerHTML? But how can I use I don't know. And using innerHTML is good for programing?
Upvotes: 4
Views: 418
Reputation: 20980
try
function result()
{
var a, b, c;
a = 10;
b = 20;
c = a+b;
var result = "The result of a+b is" + c;
document.body.appendChild(document.createTextNode(result));
document.body.appendChild(document.createElement("br"));
}
This way, you will not need to create an additional node, to hold the result data.
Upvotes: 0
Reputation: 382
document.write ALWAYS starts a new page unless there is one currently being loaded. Once the current page has finished loading any document.write statements will write to the NEXT web page to be displayed, not the current one because that one is already written.
use DOM methods like this one :
<script type="text/javascript">
function result()
{
var a, b, c;
a = 10;
b = 20;
c = a+b;
document.getElementById('foo').innerHTML = "The result of a+b is" + c;
return false
}
</script>
<span id="foo"></span>
<input type="button" value="Result" onclick="return result();">
Upvotes: 3
Reputation: 1325
Change the method result:
function result()
{
var a, b, c;
a = 10;
b = 20;
c = a+b;
document.getElementById('result').innerHTML="The result of a+b is" + c;
}
and then put in the body a div with an id result:
<div id="result"></div>
Upvotes: 0
Reputation: 1596
This would write the result in a seperate element without overwriting the whole document:
<script type="text/javascript">
function result()
{
var a, b, c;
a = 10;
b = 20;
c = a+b;
var result = document.getElementById("result");
result.innerHTML = "The result of a+b is" + c;
}
</script>
<input type="button" value="Result" onclick=result();>
<div id="result"></div>
see http://jsfiddle.net/AcTM2/
Upvotes: 0
Reputation: 11048
Any document.write() must be called before the page finishes to load, otherwise it will open a new page (see this link for help) so maybe that's your problem
you may want to do something like
function result()
{
var a, b, c;
a = 10;
b = 20;
c = a+b;
var content = document.getElementById('result_div').innerHTML;
content += "The result is ..." ;
}
Upvotes: 1
Reputation: 4539
Try this code
function result()
{
var a, b, c;
a = 10;
b = 20;
c = a+b;
console.log("The result of a+b is" + c);
}
Upvotes: 0
Reputation: 150273
If it's for debug purpose, use console.log(value)
, otherwise, yes, save the value in innerHTML
.
console.log("The result of a+b is" + c);
alert("The result of a+b is" + c); // For very old browsers.
using the innerHTML
property:
document.getElementById('{id}').innerHTML = "The result of a+b is" + c;
Upvotes: 0