I'm new here and new to using javascript, I need help with creating a prompt that asks a user for their name and then displaying the name in a confirm box. If the name is correct it has to display a message that says "Hi" followed by their name. If its not correct it has to loop through and ask for name again. So I understand how to write a prompt and confirm box separately but I am struggling with putting the prompt and confirm together with a loop.
Here is what I have so far:
var name = prompt('What is your name?');
var confirm = confirm('Is your name: ' name);
function myFunction() {
var txt;
if (confirm === true) {
txt = "You pressed OK!";
} else {
txt = "Input your correct name";
}
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You basically just need to bootstrap myFunction
, and also place the prompts inside the myFunction
so they get called again if the confirmation is false.
eg.
function myFunction() {
var name = prompt('What is your name?');
var conf = confirm('Is your name: ' name);
if (conf === true) {
alert("You pressed OK!");
} else {
alert("Input your correct name");
myFunction();
}
}
myFunction();
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
I have encapsulated your code a function and call the function again if the confirmation is no.
Here, I am passing an extra parameter, which confirms if the questions are asked first time. If it not asked first time, then it will show Input your correct name. also.
function askAndConfirm(isFirst){
var question="";
if(!isFirst) question = "Input your correct name. ";
var name = prompt(question 'What is your name?');
var isConfirm = confirm('Is your name: ' name);
if (isConfirm === true) {
alert("Hi! " name);
} else {
askAndConfirm(false);
}
}
askAndConfirm(true);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>