How can I make my online alert appropriate if the user responded to what I received on the command line?

I want to know how to warn "Unfortunately, it looks like you didn’t enter anything" if the user has enter "Enter your name". I have if and and elseif, but I don't know if it will still work for it. Here is my code

<!DOCTYPE html> <html> <head> <title>Home</title> <link rel="stylesheet" type="text/css" href="style.css"/> </head> <body style="background-color: silver"> <script> var name=prompt("Enter your name", "Enter your name") if (name !== '') { alert("Welcome" + " " + name) } else if(name !== false) { prompt("Oops, looks like you didn't enter anything"); } </script> </body> <html> 
+4
source share
4 answers
 <script> var name=prompt("Enter your name", "Enter your name") if (name!=='' && name!=='Enter your name') { alert("Welcome" + " " + name) } else if(name!==false) { prompt("Oops, looks like you didnt enter anything"); } </script> 

Demo

0
source

This method defines the getName () function, which takes the same arguments as prompt (). If no default value is specified, it uses the question that was passed to it. He then requests a username using these values. If the user returns a response that is unsatisfactory, that is, falsy (name === '', name === null, etc.) Or equivalent to the invitation we provided them, we will issue a new invitation with an error message, but the same default message.

 function getName(ques, def) { def = def || ques; // Make default param optional var name = prompt(ques, def); if (name && name !== '' && name != def) { return name; } else if(name !== false) { return getName("Oops, looks like you didn't enter anything", def); } }; var name = getName("Enter your name"); alert('Your name is: ' + name); 

Demo: http://cdpn.io/rlJGj

Be careful with this prospect. This is terrible for many reasons. If the user clicks on cancel, it will request them until they enter an acceptable value and are pressed. It doesn’t do for a better user experience, it’s pretty bad, actually.

+1
source

If you look at the definition of the JavaScript () method , you will see that the second parameter is the default text, which the return method should use if the user has not added anything.

Try this instead:

 var name = prompt("Enter your name"); if (name === "") { prompt("Oops, looks like you didn't enter anything"); } else if(name != null) { alert("Welcome" + " " + name); } 

Hope this helps! Demo here .

0
source

else if(name !== false) will always be true .

since the name will never contain true ; === does not perform type conversion .

So a little clean up:

 var pHolder = "Enter your name" var name=prompt("Enter your name", pHolder ) if(!name ||name == pHolder){ alert("Oops, looks like you didnt enter anything"); } else{ alert("Welcome" + " " + name) } 
0
source

Source: https://habr.com/ru/post/1497530/


All Articles