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.
source share