Reputation: 61
I am doing a project in a Javascript course and I need to check the conditions to make sure that the correct information is being passed in.
I am trying to learn to think like a programmer so my first solution only checked the conditions once. Seeing that as a problem I tried to think of a way to keep checking the conditions until all the information was correct. I am trying to use a while loop but I am not able to get it working.
My logic is as long as lastname is not equal to NaN OR lastname.value is less the 4 char long OR lastname is equal to null. Keep asking for there last name. If any of those conditions are true keep asking for there last name until they are all false.
I want to use a while loop for the gender prompt to but I am not sure what I am doing.
I am new and not really sure where I went wrong in this?
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Conditionals</title>
<script>
/*
Write the greetUser() function that prompts the user
for his/her gender and last name and stores the results
in variables.
For gender:
If the user enters a gender other than "Male" or "Female",
prompt him/her to try again.
For last name:
If the user leaves the last name blank, prompt him/her to
try again.
If the user enters a number for the last name, tell the user
that a last name can't be a number and prompt him/her to try again.
After collecting the gender and last name...
If the gender is valid, pop up an alert that
greets the user appropriately (e.g, "Hello Ms. Smith!")
If the gender is not valid, pop up an alert
that reads something like "XYZ is not a gender!"
*/
function greetUser() {
var gender, lastname;
gender = prompt("are you a Male or Female? ");
if (gender != "Male" && gender != "Female") {
gender = prompt("Try again: Male or Female?");
}
lastname = prompt("And what is your last name?")
while (lastname != NaN || lastname.value < 4 lastname == null); {
lastname = prompt("Please try again. What is your last name?");
}
}
</script>
</head>
<body onload="greetUser();">
<p>Nothing to show here.</p>
</body>
</html>
Upvotes: 0
Views: 1412
Reputation: 33726
function greetUser() {
var gender, lastname;
gender = prompt("are you a Male or Female? ");
while (gender !== "Male" && gender !== "Female") {
gender = prompt("Try again: Male or Female?");
}
lastname = prompt("And what is your last name?")
while (lastname === '' || lastname.length < 4 || lastname === null) {
lastname = prompt("Please try again. What is your last name?");
}
}
greetUser();
I made little fixes to your code.
while (lastname === '' || lastname.length < 4 || lastname === null)
Further, you were comparing lastname !== ''
.while (gender !== "Male" && gender !== "Female")
.Hope it helps!
Upvotes: 2