0

Hello, I've get very elementary problem with javascript

I add onclick option to one of paragrahps, but it doesn't work properly,

It should display result of my new function, but it display result in a new, empty page.
(My function work properly, but connecting it with onclick and button is out of order)

Here's the code

function adding()
{   
var piece1, piece2, result;

piece1=window.prompt('give first figure','');
piece2=window.prompt('give another figure','');

if (Number(piece1)) document.write('The first figure is okay!<br/>');
else {window.alert('Give proper figure!'); document.write('The first figure is wrong')};

if (Number(piece2)) document.write('The second figure is okay!<br/>');
else {window.alert('Give proper figure!'); document.write('The second figure is wrong')};

piece1=parseInt(piece1);
piece2=parseInt(piece2);

result=piece1 + piece2;

document.write(result);

return false;
};

</script>

<p onclick="adding()">Click to display result</p> 

[ I guess that function could be smarter, but it's not the point - it's working but when I use onclick, it starts in a new card,on a new page)

Could You tell me what is wrong with my code? I will be grateful for all advices, however basic they may be :)

Edited by pyTony: fixed formatting

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by Willy Blore
0

Willy,

Your code is calling document.write() after the page has finished loading. This will quite likely invalidate the HTML document tree. You browser would not have been expecting further data, so could this explain the problem you're seeing?

One possible solution would be to create another element. If you give the element an 'id', you'll then be able to reference it later on, by using document.getElementById(), and update the content of that element. That way you'll keep the structure of your HTML document intact.

For example:

<html>
<head>
<title></title>
<script type="text/javascript">
    function adding() {
        var p = document.getElementById('p1');
        p.innerHTML = "some result";
    }
</script>
</head>
<body>
<p onclick="adding(); return false;">Click to display result</p>
<p id="p1"></p>
</body>
</html>

Edited by LaxLoafer: Refinements ;-)

0

Thanks for reply and code. Yes, indeed, using innerHTML instead of document.write
has fixed the problem.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.