Beginner: the browser hangs when calling a function

I just started learning JavaScript and wondering why this simple snippet hangs when I click on the Call Function button. What am I missing?

<html> <head> <script type="text/javascript"> function myfunction() { document.write("hello"); } </script> </head> <body> <form> <input type="button" onclick="myfunction()" value="Call function"> </form> </body> </html> 
+4
source share
6 answers

You need to write inside the element or give the element a value, or you must use the document entry as follows:

 <html> <head> <script type="text/javascript"> function myfunction() { document.getElementById("lblMessage").innerText = "hello"; document.getElementById("txtMessage").value = "hello"; //document.write("hello"); } </script> </head> <body> <form> <script type="text/javascript"> document.write("This is written while page processed by browser !<br />"); </script> <input type="text" id="txtMessage" /><br /> <span id="lblMessage"></span><br /> <input type="button" onclick="myfunction()" value="Call function"> </form> </body> </html> 
+3
source

If you just want your button to do something, try:

 alert("Hello"); 

instead of document.write.

+3
source

Where do you expect the function to output its "hello"? Right in the button source code? It's pointless. The browser is messy and hanging.

Document.write does not magically insert something at the end of your document. He writes his materials right where he is called.

+1
source

Not too sure what you mean by β€œfreezing” ... Try this ... You can delete the warnings, but will tell you where it is in progress ...

 <html> <head> <script type="text/javascript"> function myFunction() { //for debugging alert('Made it into function'); document.getElementById('MyOutputDiv').innerHTML = 'Word To Your Mom...'; //for debugging alert('function complete'); } </script> </head> <body> <input type='button' onclick='myFunction();' value='Call Function'> <br> <div id='MyOutputDiv'></div> </body> </html> 
+1
source

document.write, but where? You must indicate this.

 <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Hello</title> </head> <body> <pre><script type="text/javascript"> function myfunction() { d = document.getElementById('hello'); d.style.display = "block"; d = document.getElementById('callme'); d.style.display = "none"; } </script> </pre> <div id="hello" style="display:none"> Hello </div> <div id="callme"> <input type="button" onclick="myfunction()" value="Call function"> </input> </div> </body> </html> 
0
source

I cannot explain the β€œfreeze”, but please take a look at this primer page on document.write: http://javascript.about.com/library/blwrite.htm I would also like to reiterate what you probably want write a specific element on a page, not just rewrite the entire page.

0
source

All Articles