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.
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 am writing a simple program for school and running into trouble with an issue I am hoping someone could help me with
These are the assignment parameters:
Create a small JavaScript program that:
Creates a variable 'total' with a value of 0.
Use a do-while loop & function to prompt the user to enter a series of numbers, or the word "quit" - the quit command should be case insensitive.
If the user enters a number, add the new number to a running total.
If the user enters the word "quit" the loop should stop execution.
If the user enters a word other than quit the prompt message should change to let the user know they entered an invalid data type
When the loop is exited, display a message giving the total of the numbers entered
My code achieves all assignment parameters except I can't figure out how to get the prompt to disappear after the quit command is entered. The result still displays on the screen but the prompt keeps looping.
Here is my code:
var inputCounter = 0;
var total = 0;
newInput = null;
quit = /quit/i
function askForNum(a) {
do {
var newInput = prompt(a);
if (!newInput.match(quit)) {
if (newInput < "A" && newInput > "" ) {
var addThis = parseFloat(newInput);
}
if (isNaN(newInput)) {
askForNum("That wasn't a number! type \"quit\" to see the results!");
} else {
total += addThis;
inputCounter++;
askForNum("Every number you enter gets added together! type \"quit\" to see the results!");
}
}
} while (!newInput.match(quit)) {
document.getElementById("addition-script").innerHTML = "<b>TOTAL:</b> " + total + "<br><b># OF ENTRIES:</b> " + inputCounter;
return;
}
}
if (total == 0){
askForNum("initial: Every number you enter gets added together! type \"quit\" to see the results!");
}
You are calling the askForNum function from inside itself (recursion), in effect starting a new do-while loop inside the previous one every time you type anything other than "quit".
We're displaying five input fields to user. He can type some information in them. After that, we need to find out if his input is correct. For that purpose we use an array of possible correct values.
Like:
var input = document.getElementById("input").value;
input = input.toLowerCase();
inputPos = possibleInputs.indexOf(input);
inputPosArray.push(inputPos);
The code for analysis looks like that for now:
function arrayLookup() {
var inputCorrect = true;
inputPosArray.forEach(function(item, i, inputPosArray) {
if (inputPosArray[i] == -1) {
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
wrongInputsArray.push(wrongInput);
inputCorrect = false;
} else {
null;
}
});
if (inputCorrect == false) {
alert("Wrong input! Check field " + wrongInputsArray);
} else {
nextStep();
}}
For now it correctly finds out if input is wrong and alerts user.
The problem is in "wrongInputsArray" - it doesn't display output correctly. E.g. if user has typed wrong information in 2nd field, it will print out "2".
But if he has made mistakes in 2nd and 5th field, he gets "Wrong input! Check field 2,2" alert.
Please show me what am I doing wrong.
Kindly yours,
Richard
You are using this code to insert the wrong asnwers:
wrongInput = cardRPos.indexOf(cardRPos[i]) + 1;
If two questions has the same answer, indexOf will return always the first match. Try just using this:
wrongInput = i + 1;
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.