JavaScript Prompt() method - javascript

I have an assignment I'm working on and I am having a problem with the prompt() method. I see that I can do one prompt, but I need several and with amounts.
For Example...
I have created an HTML table with many artists and columns with DVD's, CD's and Audio. All with prices in their rows. I need to write a prompt that will do this.
Using the prompt() method, ask the user to enter the artist's name, the number of DVD's, the number of CD's and the number of audio cassette's the user wishes to purchase. Save the answers in seperate variables. Also use a seperate prompt for each value.
Any advice would be so appreciated!
Edit: code from comment below:
var w=window.prompt("please enter your name");
window.alert(w);
var x=widow.prompt ("Enter how many DVDs you want to buy");
window.alert(x);
var y=window.alert ("Enter how many CDs you want to buy");
window.alert(y);
var z=window.alert ("Enter how many Audio Cassettes you want to buy");
window.alert(z);

From the sounds of it, the following meets your requirements:
var a, d, t;
while ( ! a ) a = prompt( "Which Artist?" );
while ( ! d ) d = prompt( "How many DVDs?" );
while ( ! t ) t = prompt( "How many tapes?" );
alert( "You want " + t + " Tapes, and " + d + " DVDs, of " + a + "." );
Let's break it down you so have an understanding of what's going on:
var a, d, t;
On the first line, I'm declaring the various variables I plan on using in the code below. This is a common practice, and would be a good habit to develop if you want to maintain clean and manageable code.
while ( ! a )
The while loop is a loop that will run over and over, until a condition is met. In this example, we're telling the loop to run as long as we don't have a value for a. What comes next is our attempt to collect a value of a from the user:
while ( ! a ) a = prompt( "Which Artist?" );
Each time the while loop runs, we will prompt the user to answer the question. We take their answer, and assign it to a. If they entered nothing, our while loop runs again, prompting them again. You can probably make sense of the next two while loops at this point.
Lastly is our alert, which gathers up the various values and shows them to the user:
alert( 'Artist ' + a );
This also presents an example of string concatenation, or joining together of two strings. We have a value stored inside a, and a value written explicitly as text. We use the + operator to join both of these together, like glue tying two ends of a rope together. As we add more strings, and more variables, we use the + operator more and more:
alert( "You want " + t + " Tapes, and " + d + " DVDs, of " + a + "." );
When this code is ran, t, d, and a will all be replaced with the actual values inserted by the end-user.
Note, this is a very basic implementation of what your homework requires. A real solution would test the type of input to make sure it's of the expected format. For instance, when asking how many DVDs the user wants, you may want to restrict 'acceptable' answers to integers only.
Best of luck!

Use a loop over the values object/array. Maybe use a second (nested) loop to prompt again until a value was entered.

Use multiple functions such that on click of the first prompt the other function gets called which handles another prompt where u can save the variable value seperately.use it recursively.

prompt is pretty easy,
this is how I use it:
var value = prompt( message );

Related

What is the least issue prone way to separate the first set of numbers from a string?

For context, I have a system that asks a user to give a rating between 1-10. Afterwards, I give them the option to leave any additional notes they would like to leave.
Unfortunately what seems to happen half of the time is that a customer will leave notes along with the initial 1-10 rating. With the interface I am using I have no way of restricting the input to numbers only.
The best solution I would be going for is to simply separate the number from the statement into two separate variables or into an array[0-1].
So basically I have
var responseA = (customer input here)
Then I would need to remove any additional comments they put into the first response
responseA = responseA.someMagic() //This is where I need help
And continue to deal with the remaining interactions and store them as such
var responseB = responseA[1] + ". " + (customer input 2 here)
This will take the second portion of the first response that includes notes and combines those notes with the second response which contains the second portion of notes. If it's possible to have some sort of way to detect that there were notes in the first place that would also be good to avoid
". Thank you."
as opposed to
"Thank you."
Because of the concatenation of the first string in situations it is not necessary.
edit: After rereading this it still seems confusing if you don't know exactly what is going on. Let me show you a real world example:
Q1: Please give a rating between 1-10:
"10! You were very helpful, thank you!"
Q2: If you have any notes you may leave them here:
"Very helpful."
This means that when the system that deals with the ratings from question 1 receives additional strings, it won't count it as a number. I want to remove everything after the 10 and add it to Q2's response to not lose any of their response, but also not store it in the wrong place.
Here is a possibility, using regex to check and split apart the first value:
const combineResponses = (q1, q2) => {
const matches = q1.match(/^(\d*)\W*(.*)/)
return matches[2] ? {
rating: matches[1],
comment: [matches[2], q2].join('. ')
} : {
rating: matches[1],
comment: q2
}
}
console.log(combineResponses(
"10! You were very helpful, thank you!",
"Very helpful."
))
console.log(combineResponses(
"10",
"Very helpful."
))
console.log(combineResponses(
"oops",
"Very helpful."
))
It does nothing to check that the rating is in the right range. Nor does it handle, say 7.4, although it would be easy enough to modify for the latter.
But if you can find a way to separate your initial input in a cleaner way, it would definitely be better to avoid this.
If you are sure the string will always begin with a number for the rating, you could call parseInt() on the string to find out what the number is. If there is a number, you could then use indexOf() to find the first time it appears and cut the string there, otherwise just assume the whole thing was a string.
const userInputs = ['1 thank you', '10thanks', ' 5. random text', 'no rating'];
let length = 1;
let index;
let rating;
let response;
for (const i of userInputs) {
rating = parseInt(i);
if (rating) {
if (rating > 9) {
length = 2;
}
index = i.indexOf(rating);
response = i.substring(index + length).trim();
} else {
response = i;
}
console.log(`${i}, rating: ${rating}, response: ${response}`);
}

Converting a String into a list of computing steps: Is it possible?

I'd like to ask wether there is a way to evaluate javascript terms multiple times without needing to parse a term over and over and over again.
Say, you want to evaluate
var1/var2+Math.sqrt(var3)
20 times a second.
This could be problematic when using
ScriptEngine.eval(string)
continueously, because you would have to replace "var1" every single time, then parse it and then let the script engine figure out the order of operations you want to perform.
Is there any alternative way?
Say, you have a configuration file in which a user gets to specify variables which increase and decrease after certain events.
You have a fixed term which javascript needs to process and the user also gets to define, but the variables change.
So is there a way to save a term as a list of operations (which internally speaking, it is) into which you only need to input the variables?
So basically, is there a way around parsing and creating an operation order over and over?
You could evaluate the expression wrapped in a function:
var expression = "var1/var2+Math.sqrt(var3)";
eval( 'function myTest(var1,var2,var3){ return ' + expression + "}" );
console.log(myTest, myTest(1, 2, 9) );
I think you are looking for a for loop.
var x = //number of time you want to run
for (i = 0; i < x; i++) {
//code...
}
or a while loop
while (condition is true) {
//code...
}
Just switch out the variables as needed to adjust how long the process runs. Or really anything else you need to adjust.

Create javascript string with conditional and non conditional variables

I'm creating a single string using some defined variables like so:
var name = 'John';
var business = 'Google';
var email = name + ' registered the business ' + business;
In reality this is from a form submission so the variables will be set in a form and sent to my NodeJS backend to create this string. The user may or may not enter a message. I've created an if statement to add it to the string if they have:
if (message) email += '<br /><br />Message: ' + message;
The problem is when I expand this logic, it can get very messy. For example if I want to add several conditional variables to various points in the middle of the original string. Is there a way to do the conditional logic inside the initial string build?
Use a ternary operator. It can still get messy, but it reduces "if" everywhere.
var email = name + ' registered ' + business
+ (message ? '<br /><br />Message: ' : '') // conditional line
+ more_stuff...;
There are many ways you could structure the code to clean things up. A simple solution would be creating an object that keeps track of your various inputs, and then you could loop through that object to append all necessary items.
For example:
var obj = {
message: messageField,
messageTwo: messageTwoField
}
for (keys in obj){
if (key == message && obj.key) {
//append the string to a specific place
}
}
There are many ways to potentially solve this, but by storing everything in one object that can help to clean things up. Also, the if statement is conditional based on the key name and if there is a value assigned to that key name. This of course is just my opinion on how you could approach this, the size and complexity of the app could greatly change this answer.

Adding and Displaying Array Issue

var reset = function ()
{
var p = parseFloat($("#IA").val());
var q = parseFloat($("#IB").val());
var m = parseFloat($("#CGCD").val());
var aR = [];
aR += ["GCD(" + p + "," + q + ")=" + m];
document.getElementById("PGCD").innerHTML = aR + "\n";
document.getElementById("IA-error").innerHTML="";
document.getElementById("IB-error").innerHTML="";
$("#IA").focus();
};
The code above is only for a 'reset' function, a part of additional code (not present), the purpose which is to find the Greatest Common Denominator, GCD.
My 'reset' function is connected to a button, #reset, the purpose of which is to do four things:
add and store the string GCD(p,q)=m to the array 'aR'; p/q/m are variable stand-ins for the values of the input text areas #IA, #IB, and #CGCD (the GCD of #IA and #IB);
display the array 'aR' in a text-area #PGCD each time the reset button is clicked; this is why I used an array;
clear the two input text areas #IA and #IB;
clear the one output text area;
As it stands, all four objectives are completed successfully, with one exception: for the second objective, only the most recent GCD calculation is outputted; none of the previous calculations output.
I cannot get the array to list the different saved calculations within it. I think (?) the new calculations are being added to the array, but I am not sure.
I've tried a 'for' statement, and an 'if' statement, neither of which worked. I don't know whether I coded it wrong, or if it wasn't the right solution for my issue.
I tried to search the forums (here) for a solution, but was unable to find one.
Thank you.
If I'm understanding what you are describing, I believe your problem is that you are attempting to use += to add elements to an array. You should use
aR.push("GCD(" + p + "," + q + ")=" + m);
The += operator is used for addition of a value to itself as well as string concatenation.
Edit: per comments below, the main issue was declaration of aR as a local variable. It needs to be either global or declared within the same scope.

Js Password Array

My Homework
"Create a basic web page that will update Assignment 3.4. Create an array that will store at least eight valid passwords. Then, ask the user for a password using a prompt dialog. Utilize a for-loop to navigate the password array. If the user's input matches any string in the array, give them feedback that the password is valid. Otherwise, let them know that it is invalid.
You do not necessarily have to include any feature that give them a chance to re-enter the password. This can simply be a one-time search of the password array."
This is for my javascript class... so far I have this:
var accepted_passwords = new Array ( );
accepted_passwords[0] = "Saginaw";
accepted_passwords[1] = "Bay City";
accepted_passwords[2] = "Midland";
accepted_passwords[3] = "Reese";
accepted_passwords[4] = "Millington";
accepted_passwords[5] = "Frankenmuth";
accepted_passwords[6] = "Sheilds";
accepted_passwords[7] = "Birch Run";
var random_bg = new Array ( );
random_bg[0] = "#0000CC";
random_bg[1] = "#33FF33";
random_bg[2] = "#990000";
random_bg[3] = "#9900FF";
random_bg[4] = "#CC0000";
random_bg[5] = "#FF00CC";
var enterpassword;
enterpassword = prompt("Enter Password", "");
for(0 <= i <= 7; enterpassword = accepted_passwords[i];) {
document.body.style.background=random_bg[Math.floor(Math.random()*random_bg.length)];
}
Its supposed to ask for a password... and then if you get it right... it displays one of the five random colors. The random color part works... its the password part that doesn't. I can do this no problem with an if else statement... but apparently my teacher wants a for loop?????? Please help!
I think the answer here is that you've fulfilled the teacher's requirement to use a for loop. However there is nothing stopping you also use one or more if..else constructs too. In fact, if you think about it a bit more, you'll realise there is no way to "check if its a valid password" without an if..else.
A few observations on how to complete your homework:
Your for(...) loop is wrong. for loops always follow the pattern:
for([loop-variable-initialisation];[loop-termination-condition];[loop-variable-increment]
eg, for(var i=0;i<10;i++) // loops for values from 0 to 9
Instead of hard-coding the length of the array, for use in the loop termination condition, it is better to read the .length of the array
You are currently not checking the value entered exists in the array at all. Worse, your actually (trying to) assign each value in the array to the variable holding the user's input: enterpassword = accepted_passwords[i]. This is wrong.
Don't take the statement so literally. He probably means: Use a loop and other required features.
On a side note I would rather use a if(x in y) construct, like described here
EDIT: Removed actual solution.

Categories