I'm following tutorial cideon on JavaScript and wrote some examples in Notepad++ and saved them as something.html. The problem is when I open it with IE or Chrome, the code between <script> and </script> tags doesn't run at all. What is wrong with that?
<!doctype html>
<html>
<head>
<title>Example of prompt()</title>
<script>
var user_name;
user_name = prompt("What is your name?");
document.write("welcome to my page ")
+ user_name + "!");
</script>
</head>
</html>
-
2document.write("welcome to my page " + user_name + "!"); try thisAkhilesh Singh– Akhilesh Singh2016年04月20日 08:43:35 +00:00Commented Apr 20, 2016 at 8:43
-
1Look at the console. You will see an error there...user5653854– user56538542016年04月20日 08:44:18 +00:00Commented Apr 20, 2016 at 8:44
-
you have a syntax error (closing a parentheses too early)PA.– PA.2016年04月20日 08:44:25 +00:00Commented Apr 20, 2016 at 8:44
-
Yeah, Sorry/ I missed that paranthesis.Eric Klaus– Eric Klaus2016年04月20日 08:47:08 +00:00Commented Apr 20, 2016 at 8:47
-
@LPK, where I can find errors on console?Eric Klaus– Eric Klaus2016年04月20日 08:47:55 +00:00Commented Apr 20, 2016 at 8:47
4 Answers 4
There is a syntax error in document.write statement.
Write it as follow
document.write("welcome to my page "+ user_name + "!");
Comments
There is one too many ")"
document.write("welcome to my page " + user_name + "!");
Comments
When you open in chrome. Press F12 or Right Click> Inspect Element. Make sure you select "Console" at the top. Pay attention and try to understand what the console tells you.
In your case, this is what it says when I paste that code into my console:
"Unexpected token" This means that it can't understand the script, it was expecting a ; or a new line because you have a bracket at the end. Remove that and it should work.
Comments
First, move the script part out of the head to the body tag.
Second, write
document.write("welcome to my page " + user_name + "!");
in one line and remove the first closing parenthesis.
<!doctype html>
<html>
<head>
<title>Example of prompt()</title>
</head>
<body>
<script>
var user_name;
user_name = prompt("What is your name?");
document.write("welcome to my page " + user_name + "!");
</script>
</body>
</html>
1 Comment
document.write in the head. and a possible problem with document.write at all.