Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

User selects the number of prompt boxes to display

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);
  
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading