Confusion with prompts and alerts - javascript

<!DOCTYPE html>
<html lang="en">
<script type="text/javascript">
<!--
var Name = prompt("Enter Your Name");
var Age = prompt("Enter Your Age. This should be an integer.");
if (Age < 12) {
alert("Sorry, You must be at least 12 to enter this site!");
exit }
var Sex = prompt("Enter Your Sex. This should be a single letter input F or M");
if (Sex != "M", "F") {
alert("Sex must be a single letter F or M");
}
// -->
</script>
Im trying to get only an "M" of "F" from the Sex prompt, but I'm really not sure how to do that. Right now it gets to the end of the code and no matter what I type into the Sex prompt the alert "Sex must be a single letter F or M" pops up. Any help would be greatly appreciated, I've been stumped for a couple days now.

In JavaScript and most other similar-looking languages, you have to be fairly verbose when checking against two values:
if (Sex != "M" && Sex != "F") {
Each part (Sex != "M" and Sex != "F") is a complete != expression, and then the overall thing is an && ("and") expression.
There are other ways to do it (a switch, or a fairly obscure thing like if (!["M", "F"].includes(Sex))), but the above is the standard way to do a simple check against two values.

Related

Javascript:How to break a while loop when a condition is met to make it so that the loop is terminated when a Var is not null (Break Not Working

var Age;
Age = prompt("How old are you");
while (Age === null){
prompt("Please Cofirm You Name");
if (Age > 0 ){
break;
}
}
I am trying to make it so that the user is in a loop until var Age is not null... My goal is to make it so that you cant cancel the prompt and have to type in it. I have tried using the break; in an if statement but its not working.
When I use the break; in an if statement it continues to send the prompt
Is there another way to do this
Or is the value of var Age equal to null(even if you add an integer greater then 0) for some reason and if it is anyone know how to fix it
is there are better way to make to user type in the prompt
Thank You in advanced
var Age = prompt("How old are you?");
Age = Number(Age);
while (isNaN(Age) || Age < 1) {
Age = prompt("Please confirm your age.");
Age = Number(Age);
}
In the prompt dialog box, the user can enter anything. So we are trying to see if the user has entered a number by using Number(Age) which tries to parse the user entered value as a number, and returns a number if it is a number.
That means if the user entered value is number, then Age will have a valid number (but it might be negative, which is invalid for our use case). Anything other than a number will give either NaN or 0.
So, when you write Age = Number(Age),
Age might be assigned with a proper number (positive or negative), or
NaN (NaN stands for not a number and it is considered a type of
data in JS), or
0 when user enters space(s).
In the while loop condition, we are checking whether the user entered value is invalid. That is, is Age not a number? or is Age less than 1?.
The || operator used between these two conditions will return true if any one of these two conditions is true (in fact, if the first condition is true, it doesn't even bother to check the second condition, and simply returns true). It returns false if both of the conditions are false.
So, if the user has entered invalid input (negative number or space or string), we prompt the user till he enters a proper value.
A while-loop has a break, look at this simple example.
let a = 2;
while (a <100) {
console.log(a);
a *= 2;
if (a===16)
break;
}
Try with do-while:
let age, age2;
do {
age = prompt("How old are you?");
} while (age === "");
do {
age2 = prompt("Please Cofirm Your age");
} while (age2 === "" || age2 !== age);

Can I use a while loop to validate a prompt input?

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>
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.
Your while loop has incorrect logical operators, this the correct version: while (lastname === '' || lastname.length < 4 || lastname === null) Further, you were comparing lastname !== ''.
For the gender prompt you need to execute a while loop while (gender !== "Male" && gender !== "Female").
Hope it helps!

Require user to choose 'boy' or 'girl'

I am trying to get my user to respond to the question "are you a boy or a girl?" with one of those two choices and force them to choose one or the other.
I think I am heading in the right direction but whenever i run my code, it hiccups if choosing the second option.
What am i doing wrong?
var gender = prompt("Are you a boy or a girl?").toLowerCase();
while (gender !== ("boy" || "girl")) {
gender = prompt("Please only respond with boy or girl. Now, are you a boy or a girl?");
}
Personally I like
var gender = prompt("Are you a boy or a girl?").toLowerCase();
while (["boy", "girl"].indexOf(gender) == -1) {
gender = prompt("Please only respond with boy or girl. Now, are you a boy or a girl?");
}
The proper condition would be
while (gender !== 'boy' && gender !== 'girl'){
That's because ("boy" || "girl") will always end up as "boy", therefore the while will look like while(gender !== 'boy'). The || in this case is called a "default" operator, a clever use of the logical OR . If the value on the left side is truthy, it will use the left side value. Otherwise, it will evaluate (hence "default") the right side.

JavaScript logical operators questions?

I just don't understand how && and || work. I wrote up a small code to help myself out and it just doesn't make any sense to me. You would click a button and the startGame() would be called.
var startGame = function() {
var quizAnswers = {
name: prompt("What is your name?").toUpperCase(),
age: prompt("What is your age?"),
snack: prompt("What is your favorite type of snack out of the following: ice cream, apple, chips, cookies?").toUpperCase()
};
quizAnswers.confirmAge = function () {
while (isNaN(this.age) === true) {
this.age = prompt("The age that you entered- " + this.age + " -is not a number. Please enter a number.");
};
};
quizAnswers.confirmAge();
quizAnswers.confirmSnack = function () {
while ((this.snack !== "ICE CREAM") && (this.snack !== "APPLE") && (this.snack !== "CHIPS") && (this.snack !== "COOKIES")) {
this.snack = prompt("The snack you entered- " + this.snack + " -is unrecognized. Please enter: ice cream, apple, chips, or cookies.").toUpperCase();
};
};
quizAnswers.confirmSnack();
It would get name, age, and favorite snack and then check to see if the age is a number and the snack entered is one of the listed options. After messing with the while loop in the confirmSnack function, I figured out how to make it work, which is displayed above. But why is it && and not ||. And is there a way to shorten it like:
while (this.snack !== ("ICE CREAM" && "APPLE" && "CHIPS" && "COOKIES")) {
this.snack = prompt("The snack you entered- " + this.snack + " -is invalid. Please enter: ice cream, apple, chips, or cookies.").toUpperCase();
};
So the questions are to explain why &&(and) is used instead of ||(or) and if there is a way to shorten this code so i don't have to enter "this.snack !==" four times. I'm not an expert so please try to keep it simple.
The && operator is working just fine. This is actually a question of logic, not javascript.
You are asking the question while the answer is different from ALL of the possible answers.
It could be rewritten with || as the follwing:
while (!(this.snack == "ICE CREAM" || this.snack == "APPLE" || this.snack == "CHIPS" || this.snack == "COOKIES"))
Notice the ! operator in the beginning.
A shorter form to write it would be:
answers = ["ICE CREAM", "APPLE", "CHIPS", "COOKIES"];
while (answers.indexOf(this.snack) < 0) { ... }
Here you define a list of possible answers and you want to accept, and check if the answer is among them.
The && and || operators compare boolean values. (Boolean means true/false). That means if you execute 5 == 5 && 6 + 1 == 7 the interpreter does the following things:
Evaluate 5 == 5. The == operator returns true if both sides are equal (as you probably know). Since 5 == 5 is true, we look at the next value (if it were false, because of short circuit operators, it would return false immediately).
Evaluate 6 + 1 == 7. This is also true, so the returned value is true.
The && operator does not compare regular values such as "ICE CREAM" (well it does, but it converts it into a boolean value).
Now let's look at the code you provided:
this.snack !== ("ICE CREAM" && "APPLE" && "CHIPS" && "COOKIES")
First, the javascript interpreter executes ("ICE CREAM" && "APPLE" && "CHIPS" && "COOKIES"). Since all of those values are true, the value of that expression is true. So this comparison is essentially checking this.snack !== true, which is not what you want.
To solve your problem, I would suggest using indexOf. This checks if an element is in an array and returns -1 if there is no element. For example:
var validSnacks = ["ICE CREAM", "APPLE", "CHIPS", "COOKIES"];
while (validSnacks.indexOf(this.snack) === -1) {
// Do something
}
If you use or(||), if any of the sub-statements (e.g. this.snack !== "ICE CREAM") evaluate to true, the entire statement will be true, causing the prompt to be shown.
On the other hand, using and(&&), all of the sub-statements must be true for the entire statement to evaluate as true, which is the behaviour that you want - you only want the prompt to show if snack is not one of the 4 options.
There is no way to shorten the code in the way you suggest. One thing you could do would be to make an array with the 4 options in it and check if that array contains snack.

Is there a way to create a loop which while only stop if specific strings are entered?

What I'm trying to do is make a loop which prompts the user for information and will only stop if certain strings are entered. Specifically, I want it only to accept certain letters, both upper and lowercase. Here's what I have so far:
do
{
salesP = prompt("Enter the initial of the first name of the salesperson: ", "");
}while (salesP != "C" || salesP != "c")
Basically the while part is completely wrong and I know it. I've tried everything I can think of, and the best I can do is get it to accept a single variable. I also need it to accept d, x, and m, both cases.
Option 1
Permanent loop with an if statement, can use multiple if statements or other control structures to check for when to break.
while 1:
if(raw_input('Enter some data please:') == specialString):
break
Option 2
Part of loop
tempstring = ""
while (tempstring != specialString):
tempstring = raw_input('Enter some data please:')
Option 3:
Recursion
def dataEntry(a,b,c):
#data validation statements that fail on first iteration
#statements to prompt user about data
dataentry(a,b,c)
As far as how to check for the right string, I would recommend regular expressions. Googling for "regex" examples is much better than me trying to explain it.
Something else to play with that if you are new you should become REALLY familiar with when doing string comparison is to eliminate case from the equation completely:
do
{
salesP = prompt("Enter the initial of the first name of the salesperson: ", "");
}while (salesP.toLowerCase() != 'c')
That code is almost correct. You simply use the incorrect boolean operator in your while statement. You're using OR (||) where you should use AND (&&).
So:
do
{
salesP = prompt("Enter the initial of the first name of the salesperson: ", "");
}while (salesP != "C" && salesP != "c")
just another approach
function promptSalesP(){
var _salesP = prompt("Enter the initial of the first name of the salesperson: ", "");
if(_salesP.toLowerCase() == "c")
return _salesP;
else
return promptSalesP();
}
var salesP = promptSalesP();

Categories

Resources