Why does this html code redirects to blank page? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why does this html code redirects to blank page?

<html> <head> </head> <body> <td><p>Input your name</p><input type="text" name="name" id="name"></td> <script type="text/javascript"> var aa = document.getElementById("name").value; </script> <button onclick='document.write(aa)'>button</button> </body> </html> After clicking button it redirects to a blank page while I expect it to print the "name" written in the field.

18th Sep 2018, 3:50 PM
Parsa Gholipout
Parsa Gholipout - avatar
2 Answers
+ 4
Parsa Gholipout It's happening because: 1. The document is read from top to bottom. 2. When the javascript runs, there is nothing in the field because the document isn't done loading yet. aa is set to an empty string. 3. When the document finishes loading, the document is closed. Any new document.write() will erase this document. 4. When the button is clicked, the previously-loaded empty value is accessed. 5. Because of step 3, document.write erases the current document and opens a new one. 6. You write an empty string. Replace line 9 in your source with this to prove statement 6 above: <button onclick='document.write("[" +aa + "]")'>button</button>
18th Sep 2018, 5:38 PM
Kirk Schafer
Kirk Schafer - avatar
+ 8
good question and thanks for the information 💖🙌
19th Sep 2018, 7:39 AM
NimWing Yuan
NimWing Yuan - avatar