So I've been at it for a while now but have no idea on how to proceed. My code asks the user for first name, last name and age of 3 people and then displays it into a table.
<script>
function person(firstName, lastName, age) {
for (var x = 1; x <= 3; x++) {
this.firstName = prompt("Please enter a first name", "");
while (this.firstName == null || this.firstName == "") {
this.firstName = prompt("Invalid input. Please enter a first name", "");
}
this.lastName = prompt("Please enter a last name", "");
while (this.lastName == null || this.lastName == "") {
this.lastName = prompt("Invalid input. Please enter a last name", "");
}
this.age = prompt("Please enter an age", "");
this.age = parseInt(this.age);
while (this.age == null || isNaN(this.age) || this.age < 0) {
this.age = prompt("Not a valid input. Please enter an age", "");
this.age = parseInt(this.age);
}
}
}
var personDetail = new person ();
document.writeln("<table>");
document.writeln(" <tr>");
document.writeln(" <th>First Name</th>");
document.writeln(" <th>Last Name</th>");
document.writeln(" <th>Age</th>");
document.writeln(" </tr>");
for (var z = 0; z < 5; z++) {
document.writeln(" <tr>");
document.writeln(" <td>" + personDetail.firstName + "</td>");
document.writeln(" <td>" + personDetail.lastName + "</td>");
document.writeln(" <td>" + personDetail.age + "</td>");
document.writeln(" </tr>");
}
document.writeln("</table>");
</script>
I know that I have to collect the user input into an array, but i don't know how.
I've tried the following. Just taking the first name as an example:
<script>
function person(firstName[]) {
for (var x = 1; x <= 3; x++) {
this.firstName[x - 1] = prompt("Please enter a first name", "");
while (this.firstName[x - 1] == null || this.firstName[x - 1] == "") {
this.firstName[x - 1] = prompt("Invalid input. Please enter a first name", "");
}
}
}
var personDetail = new person();
for (var z = 0; z < 3; z++) {
document.writeln(personDetail.firstName[z]);
}
</script>
I know there are easier ways to do this but I need to use an object with a constructor function.