var password = prompt('Please enter your password.');
if (password!=="cat" && password!=="cow") {
console.log(password);
location.assign("http://www.google.com")
}
//The rest of prompts
var age = prompt("What is your age?");
var name = prompt('What is your name?');
var homeTown = prompt('Where are you from?');
var favoritDog = prompt("What's your favorite dog?");
So that's my code, (I'm a beginner and just messing around with concepts), if the incorrect password is put in, shouldn't it redirect me to google right away? Because when I run that code, it gives me all the prompts first before the redirect. Any help is appreciated, thank you.
Because doing location.assign will not stop the execution of JavaScript, it will keep going. It will do the location assignment after the sequential JavaScript finishes. Since prompt blocks the current execution, for it to finish it will need to go through the prompts. To prevent it simply add your prompts to an else:
var password = prompt('Please enter your password.');
if (password!=="cat" && password!=="cow") {
console.log(password);
location.assign("http://www.google.com")
} else {
//The rest of prompts
var age = prompt("What is your age?");
var name = prompt('What is your name?');
var homeTown = prompt('Where are you from?');
var favoritDog = prompt("What's your favorite dog?");
}
Related
So, I need the user to enter a 6-character registration number. The prompt, should repeat if the user does not enter a 6-character code or presses cancel. For context, The prompts ask the user more about their vehicle and 5 other vehicles, and then displays the information in a table.
vehicle.registration = prompt("Please enter a 6-character vehicle registration number");
if (value.length <6) {
vehicle.registration = prompt("That is not a valid response. Please enter a 6-character registration number");
continue;
else {
document.getElementById("registration" + i).innerHTML = vehicle.registration;
}
I've tried Value.length, string.length.. I'm not sure why it isn't working.
You need to access or store the value of the prompt window i.e. vehicle.registration.
Also, you can place the validation logic in a while-loop to ask until valid input is received.
See: https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt
const promptMessage = 'Please enter a 6-character vehicle registration number',
maxRegistrationLength = 6;
let vehicle = {}; // Reference scope
// The initial request
vehicle.registration = prompt(promptMessage);
// Keep validating until true
while (vehicle.registration.length < maxRegistrationLength) {
// Ask again...
vehicle.registration = prompt('That is not a valid response. ' + promptMessage);
}
// Display the valid input
document.getElementById('registration').innerHTML = vehicle.registration;
<p>Registration #<span id="registration"></span></p>
I am trying to make sure a user enters a value for the name and doesn't just leave it blank. I have a driver that calls the function and returns the name to a variable.
I've tried
if (name == null || name == "") {
getName();
}
both in the function and below the function call in the driver. I've also tried a while loop in both places. The If statement in the driver let me get by the prompt if I hit okay twice and even if I put a name in on the second time it wouldn't store it. The while loop wouldn't break even after I put a name in.
If this isn't enough code to tell just let me know.
function driver(){
var retName = getName();
}
function getName(){
var name = prompt("Enter your name");
return name;
I want the prompt to say please enter a valid name or at least just not let a user past until they enter something.
One option is to use do/while loop:
let name;
do {
name = prompt('Enter your name');
} while (!name);
console.log(name);
Just use a while loop:
var name = prompt("Enter your name:");
while (name == null && name == "") {
name = prompt("Enter your name:");
}
console.log("Valid name!");
console.log(name);
Note that the above does not deal with a whitespace-only name - so use trim too:
var name = prompt("Enter your name:");
while (name == null && name.trim() == "") {
name = prompt("Enter your name:");
}
console.log("Valid name!");
console.log(name);
I found a similar question for this same assignment but that person was using a different type of loops. I have been struggling with this assignment and even with the teacher giving me pseudo code to try to explain it further I am still having difficulties with it writing out what it's supposed to in the end.
We are supposed to create an array that holds the price of theater tickets, then make a html table that has the different level of tickets and prices that correspond with the numbers in the array. After this we prompt the user for their name and validate that they did enter something. Then we are supposed to create a function named numSeats that prompts the user for the number of
seats that they want to buy and validate that they entered a number and the maximum number of seats they can buy in one transaction is 6.
We are supposed to use a loop to
prompt the user until they enter a valid number, then create a function named seatingChoice that prompts the user for where they would like the seats to be by indicating the correct number from the table.
seartingChoice also needs to validate that they entered a number 1-4 and use a loop to prompt the user until they enter a valid number. If the user at any time hits the cancel button in a prompt we are supposed to give an alert of "Sorry you changed your mind". This is missing from my code because i haven't figured out how to do that.
When the program calculates everything and writes to the screen in the end it is supposed to write like "UsersName ordered #tickets for a total of dollaramt" but instead it writes "Null ordered null tickets for a total of $null." The following is what i have the the javascript part of the code:
var Prices = [60, 50, 40, 30];
var Usersname = prompt("Please enter your name");
while(Usersname = null)
{
Usersname = prompt("Please enter your name");
}
function numSeats () {
var seats = prompt("Please enter the number of seats you want to buy");
parseInt(seats);
while((seats = null)||(seats > 6))
{
seats = prompt("Please enter a number between 1 and 6");
parseInt(seats);
}
return seats;
}
var seatswanted = numSeats ();
function seatingChoice () {
var choice = prompt("Please enter where you would like your seats to be located by indicating the correct number from the table");
parseInt(choice)
while((choice = null)||(choice > 4))
{
choice = prompt("Please enter a number between 1 and 4, corresponding to your section choice");
parseInt(choice);
}
return choice;
}
var seating = seatingChoice();
var dollaramt = (seatswanted * Prices[seating-1]);
document.write(Usersname + " ordered " + seatswanted + "tickets for a total of " + "$" + dollaramt + ".");
Instead of comparison operator you are using assignment operator:
var Usersname = prompt("Please enter your name");
while(Usersname = null)
{
Usersname = prompt("Please enter your name");
}
and prompt return empty string if user wont input anything so instead of null compare it to empty string i.e, ''. so change this to:
var userName = prompt("Please enter your name");
while(userName == '')
{
userName = prompt("Please enter your name");
}
There are several errors in your code. You can try your code using jsfiddle (you can try your code properly modified here: http://jsfiddle.net/pu3s0n50/).
Your errors are that you assign Username, seats and choice instead of comparing them, i.e.:
while(Usersname = null)
should be
while(Usersname == null)
and
while((seats = null)||(seats > 6))
should be
while((seats == null)||(seats > 6))
and finally
while((choice = null)||(choice > 4))
should be
while((choice == null)||(choice > 4))
The error I do not know why this happening, but this maybe solve your issue.
var Usersname = '';
Usersname = prompt('Choose a Username:');
this works. And you need the same for the others prompt.
Also if you want seat in rang 1-6: while((seats = null)||(seats > 6)) its wrong. Change to ((seats <= 6) && (seats > 0))
Maybe this could help you.
Best regards.
I'm a rookie scripter and what I'm trying to do is: create a registration form and a calculator. If you enter a password less than 5 symbols or a username less than 3 symbols you will not be able to continue. But even if I enter an username with more than 3 symbols and a password with more than 5 symbols it still displays the error message.
The code: http://pastebin.com/KqYbDJMw
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
function triggerCalc(){
if (pw.length < 5 && user.length < 3){
alert("An error occured");
}
else {
alert("Thank you for registering to my website.");
var action = prompt("Welcome to my calculator. For addition press 1, for substraction press 2, for multiplication press 3, for division press 4 and for square root press 5:", "");
var firstNum = new Array();
var secondNum = new Array();
var result = new Array();
You want to fail if either of those conditions are true, so use || (or) instead of && (and)
if (pw.length < 5 && user.length < 3)
should be
if (pw.length < 5 || user.length < 3)
Also, you want to fetch the current values each time you do your check, so this
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
should be inside your function. Ie
function triggerCalc(){
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
The problem is you get :
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
function triggerCalc(){...
on load. So it will always be blank. To get it at the time the user clicks 'continue..' move it inside the function like so:
function triggerCalc(){
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
...
You are not too far off. The two main changes are you need to put your variable assignment inside of the function you are calling so it can get the values when the submit button is pressed.
Also you probably want to use an Or instead when validating the fields. Here is an example:
function triggerCalc(){
var user = document.forms[0].username.value;
var pw = document.forms[0].password.value;
if (pw.length < 5 || user.length < 3){
alert("An error occured");
}
If you're doing any kind of validation, there are some great jQuery libraries that make it look great and are easy to implement. You might want to to a quick google search.
Got a simple Javascript program here to accept and check a password. It should:
Ask you to enter a new password
Check the strength of the password which outputs a message of either weak or strong based on a length of <6 or >6.
Get you to re enter this password to enter the 'system'
Give you simple prompts or 2 random letters if the password is not correct.
Everything works except the strong/weak checker. It has a problem getting the length of passwordEntry since it apparently doesn't exist as an entity.
Any ideas would be much appreciated
var pass;
var main = function(){
strengthCheck((prompt("Please Choose a New Password to Begin"));
}
var strengthCheck = new function(passwordEntry){
score = 0;
// adds to the score variable depending on the length of the password
if(passwordEntry.length > 6{
score=(score+1);
}
//reads messages back stating how strong password is based on length
if(score=0){
console.log("Your Password is Weak");
}
else if(score=1){
console.log("Your Password is Strong");
}
var passContinue = prompt("Do you want to continue with this password? Yes or no?")
if(passContinue === "no" || passContinue === "No"{
main();
}
else{
pass = passwordEntry;
console.log("Your new password has been changed to " + pass);
passwordChecker(prompt("Thank You. Please Enter Your Password Below"));
}
}
var passwordChecker = function (attempt){
if(attempt == pass){
console.log("Correct password. The system has logged you on");
}
else{
//if the password is wrong, runs the incorrectpassword() function
console.log("Incorrect Password");
IncorrectPass();
}
}
}
var IncorrectPass = function (){
var clueanswer = prompt("Do You Want A Clue");
if(clueanswer === "Yes" ||clueanswer === "yes"){
console.log("I will give you two random letters");
// takes two random locations from the string array and reads them back
var randarray1 = Math.floor((Math.random()*7)+1);
var randarray2 = Math.floor((Math.random()*7)+1);
var randletter1 = pass[randarray1];
var randletter2 = pass[randarray2];
console.log(randletter1+" "+randletter2);
passwordChecker("Please try entering your password again");
}
else{
console.log("GoodBye");
}
}
main()
This part looks very wrong:
if(score=0){
console.log("Your Password is Weak");
}
else if(score=1){
console.log("Your Password is Strong");
}
You should use == or === instead of = which is used for assignment rather than comparison.
This doesn't make sense either:
var main = function(){
strengthCheck((prompt("Please Choose a New Password to Begin"));
}
There are three opening parentheses and only two closing ones. Smells like parser error.
Change this...
var strengthCheck = new function(passwordEntry){
to this...
var strengthCheck = function(passwordEntry){
When you use new, you're not using it to create a new function. You're using it to call the function as a constructor, which will return an object. (An empty object in your case.)
Also, you have many syntax errors in your code. Use a code validator like http://jshint.com as well as a beautifier like http://jsbeautifier.org to clean up your code.