+ 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.
2 ответов
+ 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>
+ 8
good question and thanks for the information 💖🙌