Home > Software design >  User selects the number of prompt boxes to display
User selects the number of prompt boxes to display

Time:11-22

Trying to write a javascript code That will enable user to select the number of prompt boxes.

Like,The prompt box will say, how many prompts do you want. Then if the user inputs 2. Two prompt box will show and if user inputs 3 or 4. That number of prompt boxes will show.

    let num = Number(prompt('Enter the number of prompts:'));

if (num=1){
  let name1 = prompt('Enter first user name:');
  let age1 = prompt('Enter first user age');
  
  
  console.log(name1)
  console.log(age1);
}
  
else if (num=2){
  let name1 = prompt('Enter first user name:');
  let age1 = prompt('Enter first user age');
  
  let name2 = prompt('Enter second user name:');
  let age2 = prompt('Enter second user age');
  
  console.log(name1);
  console.log(age1);
  
  console.log(name2)
  console.log(age2);
}
else{
  let name1 = prompt('Enter first user name:');
  let age1 = prompt('Enter first user age');
  
  let name2 = prompt('Enter second user name:');
  let age2 = prompt('Enter second user age');
  
  let name3 = prompt('Enter third user name:');
  let age3 = prompt('Enter third user age');
  
  
  console.log(name1)
  console.log(age1);
  
  console.log(name2)
  console.log(age2);
  
  console.log(name3)
  console.log(age3);
  
}

CodePudding user response:

I would just use a for loop.

let num = Number(prompt('Enter the number of prompts:'));

const data = [];

for (let i = 0; i < num; i  ) {
  let name = prompt(`Enter user ${i}'s name:`);
  let age = prompt(`Enter user ${i}'s age:`);

  data.push({ name, age });
}

data.forEach(d => {
  console.log(d.name);
  console.log(d.age);
});

Simplify it by rewording the prompts so you can use the index of the current position in the loop.

If you want everything to be logged at the end, keep all the answers in an array, and iterate through that array at the end to log the answers.

  • Related