Problem with code

kba

Joined
Apr 18, 2023
Messages
2
Reaction score
0
<script>
var name = prompt("What is your name?");
if (name != null) {
alert("Hello " + name);
}
else {
alert("You did not tell me your name. ");
}
</script>

I cannot get this code to work (I'm a rank beginner). If I enter a name and click OK, it comes back with "Hello name" as it should. BUT... if I click CANCEL, it comes back with "Hello null" instead of "You did not tell me your name". Same thing if I don't enter a name and click OK.

I have tried this in the HEAD section. In the BODY section of my html page. No difference. I've tried it as a separate js file. I've played with spacing.

Cannot get it to work. This is from a book, and other code snippets they provide work, but not this one. Any help would be greatly appreciated.
 
Joined
Sep 4, 2022
Messages
128
Reaction score
16
Hello !

read one more time about "prompt" function in Javascript :


JavaScript:
<script language="Javascript" type="text/javascript"> // mention Javascript type Mime

var answer = "Hello " ;

answer += prompt("What is your name?"); // joining response with 'answer' var. ( if one input )

if(answer.length == 6){ // "Hello " have 6 characters, never less, never more.

  answer = "You did not tell me your name. ";
// if no 'input' we replace the first String by another one.

}

alert(answer);

</script>
 
Last edited:

kba

Joined
Apr 18, 2023
Messages
2
Reaction score
0
<script language="Javascript" type="text/javascript"> // mention Javascript type Mime var answer = "Hello " ; answer += prompt("What is your name?"); // joining response with 'answer' var. ( if one input ) if(answer.length == 6){ // "Hello " have 6 characters, never less. answer = "You did not tell me your name. "; // if no 'input' we replace the first String by another one. } alert(answer); </script>

If I enter a name, this returns "Hello Beth" as it should. If I hit CANCEL, it returns "Hello null". rather than "You did not tell me your name".

I have been playing with this code all evening and finally came up with this:
<script>
var name = prompt("What is your name?");
if (name != "null") {
alert("Hello " + name);
}
else {
alert("You did not tell me your name. ");
}
</script>

The only difference being that I placed NULL in double-quotes. This works as it should.

Please know I really appreciate your response and it's been helpful in my efforts to figure this out. Thank you.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top