Javascript Prompt Box Loops - javascript

Something is wrong with this code but I can't figure out what it is. The page does not work properly or do what it's supposed to. I need a code that prompts for a password and that limits the attempts to 3. After the third attempt, it needs to have an alert box.
<script>
var attempts = 3;
var answer = prompt("Password: ");
while (attempts != 0)
{
if (answer == "Psycho")
{
document.write("These are pictures of my kitten and her things.");
}
else
{
answer = prompt("Password: ");
attempts--;
}
}
if (attempts = 0)
{
alert("Incorrect Password");
}
</script>

You have a couple of issues. You should check entry after the user enters in the prompt. Or the last entry will not be checked. Next issue is you are not exiting the loop. Another issue is the fact that = is assignment so inside the if you are assigning zero, not checking to see if it is zero.
var attempts = 3;
while (attempts > 0) {
var answer = prompt("Password: ");
if (answer == "Psycho") {
document.write("These are pictures of my kitten and her things.");
break;
}
attempts--;
}
if (attempts == 0) {
alert("Incorrect Password");
}

There are a few options to fix your code.
You could return once you're done the work.
<script>
var attempts = 3;
var answer = prompt("Password: ");
while (attempts != 0)
{
if (answer == "Psycho")
{
document.write("These are pictures of my kitten and her things.");
break;
}
else
{
answer = prompt("Password: ");
attempts--;
}
}
if (attempts == 0)
{
alert("Incorrect Password");
}
</script>
Or, I would return early if you've failed
<script>
var attempts = 4;
var answer = prompt("Password: ");
while (attempts > 0 && answer != "Psycho")
{
answer = prompt("Password: ");
attempts--;
}
if (attempts == 0)
{
alert("Incorrect Password");
}
else
{
document.write("These are pictures of my kitten and her things.");
}
</script>

Related

Attempting to nest if/else statement in while loop

I'm setting up the following while loop to continue to print a message for each even number entered but print a different message for an odd number and stop:
userEnteredNumber = prompt("Please enter a number:");
while (userEnteredNumber%2 === 0) {
if (userEnteredNumber%2 === 0) {
document.write(userEnteredNumber + EVEN_MESSAGE);
} else if (userEnteredNumber%2 !== 0) {
document.write(userEnteredNumber + NOT_EVEN_MESSAGE);
}
userEnteredNumber = prompt("Please enter a number:");
console.log(userEnteredNumber);
}
Right now it will continue to print with even number entry and stop if an odd number is entered, but the odd number message won't print. Not really understanding why the odd message won't print. Hoping someone can help clarify it for me!
More like this:
while (true) {
userEnteredNumber = prompt("Please enter a number:");
if (userEnteredNumber == null) { // they clicked cancel
break;
}
if (userEnteredNumber%2 === 0) {
document.write(userEnteredNumber + EVEN_MESSAGE);
} else if (userEnteredNumber%2 !== 0) {
document.write(userEnteredNumber + NOT_EVEN_MESSAGE);
} else {
document.write(NOT_VALID_MESSAGE + userEnteredNumber);
}
console.log(userEnteredNumber);
}
From your code, you can change it a bit to look like this:
while (true) {
userEnteredNumber = prompt("Please enter a number:");
if (userEnteredNumber%2 === 0) {
document.write(userEnteredNumber + EVEN_MESSAGE);
} else if (userEnteredNumber%2 !== 0) {
document.write(userEnteredNumber + NOT_EVEN_MESSAGE);
break;
}
console.log(userEnteredNumber);
}

How to redirect a user depending on what their input contains?

I am working on a education project that contains javascript that redirects a user to a specific webpage depending on their input like so;
function passWord(){
var testV = 1;
var pass1 = prompt('Enter First 3/4 Digits of Post Code...','');
while (testV < 3) {
if (!pass1) history.go(0);
if (pass1.toUpperCase() == "NE1") {
window.open('eligible.html');
break;
} else if (pass1.toUpperCase() == "NE2") {
window.open('eligible.html');
break;
And I wish to change the script so that rather than the user specifically enter in "NE1" or "NE2" for example, they could enter in anything as long as it contained "NE1" or "NE2"
What would be a reasonable way of doing this?
The easiest way would be with ES6's .includes() method:
function passWord() {
var testV = 1;
var pass1 = prompt('Enter First 3/4 Digits of Post Code...', '');
while (testV < 3) {
if (!pass1)
history.go(0);
if (pass1.toUpperCase().includes("NE1")) {
window.open('eligible.html');
break;
} else if (pass1.toUpperCase().includes("NE2")) {
window.open('eligible.html');
break;
}
}
}
passWord();
You could also make use of a regex, or just .indexOf() in ES5 JavaScript:
function passWord() {
var testV = 1;
var pass1 = prompt('Enter First 3/4 Digits of Post Code...', '');
while (testV < 3) {
if (!pass1)
history.go(0);
if (pass1.toUpperCase().indexOf("NE1") !== -1) {
window.open('eligible.html');
break;
} else if (pass1.toUpperCase().indexOf("NE2") !== -1) {
window.open('eligible.html');
break;
}
}
}
passWord();

random number doesn't change in loop

The random number doesn't change using while loop. When I want to play again, the randomnumber is still the same.
Here's the code:
randomnumber=Math.floor(Math.random()*10);
while(true){
yourguess=prompt("Please Enter A Number Between 1-10");
if(randomnumber==yourguess){
alert("Good Job");
answer=prompt("Do You Want To Play More ? Y/N")
if(answer=="Y"){
}else{
break;
}
}else{
alert("Not Matched "+ randomnumber);
}
}
You should repeat the generation of the random number when a next game is requested:
var randomnumber = Math.floor(Math.random()*10);
while (true) {
var yourguess = prompt("Please Enter A Number Between 1-10");
if (randomnumber == yourguess) {
alert("Good Job");
var answer = prompt("Do You Want To Play More ? Y/N")
if (answer == "Y") {
randomnumber = Math.floor(Math.random()*10); //<---
} else {
break;
}
} else {
alert("Not Matched "+ randomnumber);
}
}
Make sure to declare your variables (with var, let or const).
You need to generate that randomnumber inside the while loop:
while(true){
var randomnumber=Math.floor(Math.random()*10);
yourguess=prompt("Please Enter A Number Between 1-10");
if(randomnumber==yourguess){
alert("Good Job");
answer=prompt("Do You Want To Play More ? Y/N")
if(answer=="Y"){
}else{
break;
}
}else{
alert("Not Matched "+ randomnumber);
}
}
If you want a different random number each time the loop is executed, you need to generate the randomnumber inside the while loop.
while (true) {
let randomnumber = Math.floor(Math.random() * 10);
yourguess = prompt("Please Enter A Number
Between 1 - 10");
if (randomnumber == yourguess) {
alert("Good Job");
answer = prompt("Do You Want To Play More ? Y/N")
if (answer == "Y") {
} else {
break;
}
} else {
alert("Not Matched " + randomnumber);
}
}
You could make randomnumber a function and call it on loop start. In addition your code snippet was changed a bit in order not to get stuck in a loop of un-closing prompt windows, what was missing is a small part that checks what happens when user does not provide an answer or clicks the cancel button.
var randomnumber = function() { return Math.floor(Math.random()*10); }
while(true){
let number = randomnumber();
yourguess=prompt("Please Enter A Number Between 1-10");
if(!yourguess) {
break;
}
if(number===parseInt(yourguess)){
alert("Good Job");
answer=prompt("Do You Want To Play More ? Y/N");
if(!RegExp("y","gi").test(answer) || !answer){
break;
}
}else{
alert("Not Matched "+ number);
}
}

Google script notifies all email adresses everytime the script runs

Is there a way to make it so you do not send a notification to the user's email when using addEditor(email) on Google script. Been looking through the references for Google developers and haven't found anything.
var ss = SpreadsheetApp.openById("1aU3MOdUKHEgGRCtVaSJs3iRqRIRhLSvpCuXzOVT7Ko8")
var sheet = ss.getSheetByName("Ark 1")
var range = sheet.getRange("B:C")
//Column B is the emails, and C is a list of Edit, View, None
var range_length = range.getValues().length + 1
function scriptTesting(row) {
var scriptTesting = DriveApp.getFolderById("0B8FOoqX6_Y84eHZFaFBGTlJzMTQ")
for (var a = 1; range_length > a; a++) {
var email = range.getCell(a, 1).getValue()
var choice = range.getCell(a, 2).getValue()
if (choice == "Edit") {
scriptTesting.addEditor(email)
} else if (choice == "View") {
scriptTesting.addViewer(email)
} else if (email == "") {
break
} else if (choice == "None") {
try {
scriptTesting.removeViewer(email)
} catch(err) {
continue
}
} else {
continue
}
}
}

My javascript loop breaks before it gets through all if else statements

I'm trying to write a pin number guessing game and wrote out a bunch of if else statements but it stops working after I input the first pin (correct or incorrect), can anyone tell me what's going on?
var ans = prompt("Do you want to play?");
if (ans == "y") {
document.getElementById("ans").innerHTML = "You answered yes.";
guessNum();
if (gNum != pswd) {
document.getElementById("hint").innerHTML = h1;
guessNum();
if (gNum != pswd) {
document.getElementById("hint").innerHTML = h2;
guessNum();
if (gNum != pswd) {
document.getElementById("hint").innerHTML = h3;
guessNum();
if (gNum != pswd) {
document.getElementById("hint").innerHTML = "You lost. :(";
} else {
document.getElementById("hint").innerHTML = "You guessed the pin!";}
} else {
document.getElementById("hint").innerHTML = "You guessed the pin!";}
} else {
document.getElementById("hint").innerHTML = "You guessed the pin!";}
} else {
document.getElementById("hint").innerHTML = "You guessed the pin!";}
} else {
document.getElementById("ans").innerHTML = "You answered no.";}
Here is the rest of the javascript but I don't think the problem lies there.
var nums = [0, 0, 0, 0];
for (var idx = 0; idx < nums.length; ++idx)
{
nums[idx] = Math.floor((Math.random() * 9) + 1);
}
pswd = nums.join("")
document.getElementById("nums").innerHTML = pswd;
function guessNum() {
var gNum = prompt("What do you think the number is?")
}
if (nums[3] % 2 == 0) {
var divis = "even";
} else {
var divis = "odd";
}
var h1 = "The first number is " + nums[0]
var h2 = "The sum of the middle numbers are " + (nums[1] + nums[2])
var h3 = "The last number is " + divis
The problem is that the variable gNum that you're creating inside the guessNum function only lives there. Javascript is function scoped.
When you get to the line if (gNum != pswd) {... gNum simply doesn't exist. Make guessNum return the value, and create the actual gNum variable on the same scope as the if.
function guessNum() {
return prompt("What do you think the number is?")
}
...
var gNum = guessNum();
if (gNum != pswd) {
...
I would also advise you to study while loops, to avoid these nested ifs. Keep the hard work! :)

Categories

Resources