Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I was trying to shorten the code for returning "NO ANSWER" when one of my prompts was left blank in the code below:
var name = prompt("What is your name?");
var age = prompt("What is your age?");
var address = prompt("What is your email address?");
var credit = prompt("What is your credit card number?");
var social = prompt("What is your social security number?");
var arr = [name, age, address, credit, social];
var l = arr.length;
for (var i = 0; i < l; i++) {
if (arr[i] == "") {
arr[i] = "NO ANSWER";
}
}
alert("Your information is " + name + ", " + age + ", " + address + ", " + credit + ", and" + social + ".");
alert("Now the internet has all of your information. Have a nice day >:D");
however, the code doesn´t work. can someone tell me why?
The for loop does work and works as expected. You need to use array arr while printing or using those input variables. That's because when you do arr[i] = "NO ANSWER";, you actually set the array element to "NO ANSWER", not the original variables. See the following:
var name = prompt("What is your name?");
var age = prompt("What is your age?");
var address = prompt("What is your email address?");
var credit = prompt("What is your credit card number?");
var social = prompt("What is your social security number?");
var arr = [name, age, address, credit, social];
var l = arr.length;
for (var i = 0; i < l; i++) {
if (arr[i] == "") {
arr[i] = "NO ANSWER";
}
}
alert("Your information is " + arr[0] + ", " + arr[1] + ", " + arr[2] + ", " + arr[3] + ", and" + arr[4] + ".");
alert("Now the internet has all of your information. Have a nice day >:D");
Try this instead. It seems that you are updating arr but you are not printing arr to the screen.
var name = prompt("What is your name?");
var age = prompt("What is your age?");
var address = prompt("What is your email address?");
var credit = prompt("What is your credit card number?");
var social = prompt("What is your social security number?");
var arr = [name, age, address, credit, social];
var l = arr.length;
for (var i = 0; i < l; i++) {
if (arr[i] == "") {
arr[i] = "NO ANSWER";
}
}
alert("Your information is " + arr[0] + ", " + arr[1] + ", " + arr[2] + ", " + arr[3] + ", and " + arr[4] + ".");
I tried dry running the code with no address. following code works. The if statement need to change
testarr = function () {
var name = 'xxx';
var age = 10;
var address;
var credit = 252525;
var social = 564654;
var arr = [name, age, address, credit, social];
var l = arr.length;
for (var i = 0; i < l; i++) {
if (!arr[i]) {
arr[i] = "NO ANSWER";
}
}
return arr;
//alert("Your information is " + name + ", " + age + ", " + address + ", " + credit + ", and" + social + ".");
//alert("Now the internet has all of your information. Have a nice day >:D");
}
var t = new testarr();
console.log ("Your information is " + t[0] + ", " + t[1] + ", " + t[2] + ", " + t[3] + ", and" + t[4] + ".")
Related
I'm able to run it, fill out both Arrays, then input the search criteria but that's it. no results are thrown back.
var SIZE = 4;
var actors = new Array(SIZE); //array holding actors
var roles = new Array(SIZE); //array holding roles
for (var i = 0; i < SIZE; i++) {
actors[i] = prompt ("Please enter your " + (i + 1) + " favorite Actor");
roles[i] = prompt ("What role did your " + (i + 1)+ " Actor played?");
}
var favorite; // hold search actor name
var found = false;
var BR = "<br>";
favorite = prompt ("Please enter the name of your most favorite actor of all");
while (i < size && !(found)) {
i++;
if (actors[i] == favorite) {
found = true;
document.write("Your favorite actor " + actors[i] + " played the role of " + roles[i] + BR);
/*for(var i = 0; i < size; i++) {
if ( favorite == actors[i]) {
found = true;
document.write("Your favorite actor " + actors[i] + " played the role of " + roles[i] + BR);
}
}
*/
if (!found) { //if we find nothing
document.write("Sorry, we couldn't find an actor with that name" + BR);
}
I have tried using for and also while loop but none work, in my head the while loop makes sense. So im not sure whats the issue.
You have to update some parts:
Please use another variable then i in the second loop
Move increase of counter to the end of scope of the second loop
Use SIZE in the second loop, as JS is case-sensitive.
Please check the updated example (https://codepen.io/alekskorovin/pen/xxXxYGB):
var SIZE = 4;
var actors = new Array(SIZE); //array holding actors
var roles = new Array(SIZE); //array holding roles
for (var i = 0; i < SIZE; i++) {
actors[i] = prompt("Please enter your " + (i + 1) + " favorite Actor");
roles[i] = prompt("What role did your " + (i + 1) + " Actor played?");
}
var favorite; // hold search actor name
var found = false;
var BR = "<br>";
favorite = prompt("Please enter the name of your most favorite actor of all");
let k = 0
while (k < SIZE && !found) {
if (actors[k] == favorite) {
found = true;
console.log(
"Your favorite actor " +
actors[k] +
" played the role of " +
roles[k] +
BR
);
if (!found) {
//if we find nothing
console.log("Sorry, we couldn't find an actor with that name" + BR);
}
}
k++;
}
found the problem thanks to #Teemu, a silly mistake I made
had SIZE declared but later down I was using size.
I cant solve this homework that needs to ask the user to enter student marks and output the minimum mark of the student, can someone please help me solve this problem:
<script>
function getMarks() {
var marks = prompt('Type the students marks, seperate each student mark with comma, do not write the percentage mark % .').split(',');
return marks;
}
var studentMarks = getMarks();
var arrayLength = studentMarks.length;
var studentNumber = 0;
var msg = '';
var i;
for (i = 0; i < arrayLength; i++) {
studentNumber = (i + 1);
msg += 'student ' + studentNumber + ': ';
msg += studentMarks[i] + '%' + '<br />';
} document.getElementById('marks').innerHTML = msg; document.getElementById('marke').innerHTML = math.min.apply(null, studentMarks) + '%';
</script>
I will do that in the following way:
function getMarks() {
var marks = prompt('Type the students marks, seperate each student mark with comma, do not write the percentage mark % .');
return marks.split(',').map(n => Number(n));
}
var marksArray = getMarks();
var studentMarks = Math.min(...marksArray);
var position = marksArray.indexOf(studentMarks);
var msg = 'Student ' + Number(position + 1) + ': ';
document.getElementById('marks').innerHTML = msg + studentMarks + '%';
<p id="marks"></p>
My goal with this code is to create a makeshift shopping cart that gives the option to choose from a small selection of items, choose your quantity, get your total, remove items if you want and proceed to "checkout". My issue is, once I get the results of the price by the type of item (via alert), I don't know how to add all of the potential alerts together since it's running in a for loop. Does anyone have an idea on how to do this? I am fairly new to JS and don't know how to proceed. This is also my first question here on stack, so forgive me if it's an odd question.
Here is my code:
var item = function(itemName, itemPrice, itemTax) {
this.products = itemName;
this.cost = itemPrice;
this.taxes = itemTax;
this.total = itemPrice + (itemPrice * itemTax)
}
var list = [];
list[0] = new item("Shoes", 67.99, .075);
list[1] = new item("Coat", 78.99, .075);
list[2] = new item("Book", 9.99, .075);
list[3] = new item("Suitcase", 56.99, .075);
function theStore() {
var greeting = prompt("Welcome to xxxxxxxx! Do you want to begin shopping?");
while (greeting === "Yes")
{
for (var i = 0; i < list.length; i++)
{
var j = list[i];
var adding = prompt("The " + j.products + " cost " + j.cost + ". Would you like to add it to your cart?")
if (adding === "Yes")
{
var addingMore = prompt("How much do you want?")
if (addingMore < 1)
{
alert("This item was not added to your cart.")
}
else
{
alert(addingMore + " of " + j.products +" has been added to your cart." + " Your total for this kind of item is " + addingMore * (j.cost) + ".")
}
}
else
{
alert(j.products + " was not added to your cart.")
}
}
greeting = prompt("Do you want to continue shopping? Yes or No");
}
}
theStore()
Ideally, when the user prompts "No" (line 47) I want to show them the total of all the items.
Any help/tips/advice is appreciated.
Declare a variable totalAmount outside the loop, and add to it as the user adds things to the cart. Then when the user hits no alert the total Amount.
I added a subtotal variable that is calculated by when the user selects the quantity of items. The subtotal is the added to the variable totalAmount which is alerted at the end.
var item = function(itemName, itemPrice, itemTax) {
this.products = itemName;
this.cost = itemPrice;
this.taxes = itemTax;
this.total = itemPrice + (itemPrice * itemTax)
}
var list = [];
var totalAmount = 0;
list[0] = new item("Shoes", 67.99, .075);
list[1] = new item("Coat", 78.99, .075);
list[2] = new item("Book", 9.99, .075);
list[3] = new item("Suitcase", 56.99, .075);
function theStore() {
var greeting = prompt("Welcome to xxxxxxxx! Do you want to begin shopping?");
while (greeting === "Yes")
{
for (var i = 0; i < list.length; i++)
{
var j = list[i];
var adding = prompt("The " + j.products + " cost " + j.cost + ". Would you like to add it to your cart?")
if (adding === "Yes")
{
var addingMore = prompt("How much do you want?")
if (addingMore < 1)
{
alert("This item was not added to your cart.")
}
else
{
var subTotal = addingMore * (j.cost);
totalAmount += subTotal;
alert(addingMore + " of " + j.products +" has been added to your cart." + " Your total for this kind of item is " + subTotal.toString() + ".")
}
}
else
{
alert(j.products + " was not added to your cart.")
}
}
greeting = prompt("Do you want to continue shopping? Yes or No");
if(greeting === "No"){
alert("Your Total Amount is: " + totalAmount);
}
}
}
theStore()
var item = function(itemName, itemPrice, itemTax) {
this.products = itemName;
this.cost = itemPrice;
this.taxes = itemTax;
this.total = itemPrice + (itemPrice * itemTax)
}
var list = [];
list[0] = new item("Shoes", 67.99, .075);
list[1] = new item("Coat", 78.99, .075);
list[2] = new item("Book", 9.99, .075);
list[3] = new item("Suitcase", 56.99, .075);
var selected_items = [];
function theStore() {
var greeting = confirm("Welcome to xxxxxxxx! Do you want to begin shopping?");
while (greeting)
{
for (var i = 0; i < list.length; i++)
{
var j = list[i];
var adding = confirm("The " + j.products + " cost " + j.cost + ". Would you like to add it to your cart?")
if (adding)
{
var addingMore = prompt("How much do you want?")
if (addingMore < 1)
{
alert("This item was not added to your cart.")
}
else
{
alert(addingMore + " of " + j.products +" has been added to your cart." + " Your total for this kind of item is " + addingMore * (j.cost) + ".");
j.quantity = addingMore; // Add user selected quantity to object
j.total_cost = addingMore * (j.cost); // Add cost if user selected quantity to object
selected_items.push(j); // Let's store it in array.
}
}
else
{
alert(j.products + " was not added to your cart.")
}
}
greeting = confirm("Do you want to continue shopping? Yes or No");
return selected_items;
}
}
// theStore() Stored array can be utilised for processing.
console.log(theStore());
here is the code I've been working on.
var storeUsersInfo = [];
var amountOfUsers = prompt("How many users do you want?");
amountOfUsers = parseInt(amountOfUsers);
function returnUserInput() {
var askFirstName = prompt("What is your first name?");
var askLastName = prompt("What is your last name" + " " + titleCase(askFirstName) + "?");
var askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
if(askAge != int) {
alert("Not a valid input")
};
return {
firstName: titleCase(askFirstName),
lastName: titleCase(askLastName),
age: askAge
};
};
function titleCase(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
};
for(var i = 0; i < amountOfUsers; i++) {
storeUsersInfo[i] = returnUserInput();
}
console.log(storeUsersInfo);
I wondering how I can check the input of askAge to see if it equals a number.
I tried some code as you can see on lines 9-12 and I can't figure it out. I know it has to do something with typeof.
Thoughts?
multiply it by 1 and if it returns NaN and is not the same as the original input- its not a number
var askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
var askedAge=parseInt(askAge)*1;
if(askedAge != askAge) {
alert("Not a valid input");
}
This can be solved using a combination of Number.isInteger and Number.parseInt. Both of which have been standardized in ES2015.
The following expression will check if the age is valid:
Number.isInteger(Number.parseInt(askAge));
Note that you'll have to parse the user input to an integer first; this can either result in a valid integer or in NaN.
If it is an integer, then Number.isInteger will make the expression true; otherwise, the parsed number was NaN and the expression will become false.
I think you can you this code,
function isNumeric(x) {
return !isNaN(parseFloat(x)) && isFinite(x);
}
You could use
Number.isInteger(askAge)
Reference :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
try this
var check = /^[0-9]+$/;
var checkall = askAge.match(check);
if (!checkall){
alert("Not a valid input")
}
The cryptic answer:
var askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
if(!Number.isInteger(Number.parseInt(askAge))) {
alert("Not a valid input")
};
More:
You are partially correct in your assumption, you do have to check the type of the number to ensure that is is a number and also that it is an integer. How you actually DO that has several options. Here is one that should work.
You must determine if you wish to use Number() or Number.parseInt() as that determination will herein make a difference in the accepted values.
Given that, I choose to use the parseInt in this answer. I also constructed it to not accept 0 as a value for the number of users.
First we use or create the isInteger and parseInt in Number:
Number.isInteger = Number.isInteger || function(value) {
return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
};
Number.parseInt = Number.parseInt || parseInt;
Declare our other functions: (commented)
// this will error out if "Cancel" on the prompt is clicked (null is passed in mystring)
function titleCase(mystring) {
return mystring.charAt(0).toUpperCase() + mystring.slice(1);
}
function returnUserInput() {
var isValid = false;
var askFirstName = "";
var askLastName = "";
var askAge = null;
do {
askFirstName = prompt("What is your first name?"); // currently accepts " " as a valid name
askLastName = prompt("What is your last name" + " " + titleCase(askFirstName) + "?"); // accepts " " as a valid name
askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
isValid = Number.isInteger(Number.parseInt(askAge));
if (!isValid) {
alert("Not a valid input");
}
} while (!isValid); // accepts 0 and negative values as age
return {
firstName: titleCase(askFirstName),
lastName: titleCase(askLastName),
age: Number.parseInt(askAge) // was using the unparsed string "4' if 4 was entered
};
}
Use the functions:
var storeUsersInfo = [];
var amountOfUsers = 0;
var enteredCount = 0;
do {
amountOfUsers = prompt("How many users do you want?");
enteredCount = Number.parseInt(amountOfUsers, 10);// parse it
} while (!(Number.isInteger(Number.parseInt(amountOfUsers, 10))) && !enteredCount > 0)
amountOfUsers = enteredCount;
for (var i = 0; i < amountOfUsers; i++) {
storeUsersInfo[i] = returnUserInput();
}
console.log(storeUsersInfo);// console.dir might also work (better?)
To preface this, we are a small organization and this system was built by someone long ago. I am a total novice at javascript so I have trouble doing complicated things, but I will do my best to understand your answers. But unfortunately redoing everything from scratch is not really an option at this point.
We have a system of collecting data where clients use a login to verify a member ID, which the system then uses to pull records from an MS Access database to .ASP/html forms so clients can update their data. One of these pages has the following function that runs on form submit to check that data in fields a/b/c sum to the same total as d/e/f/g/h/i. It does this separately for each column displayed (each column is a record in the database, each a/b/c/d/e/f is a field in the record.)
The problem is with this section of the function:
for (var j=0; j<recCnt; j++) {
sumByType = milesSurf[j] + milesElev[j] + milesUnder[j];
sumByTrack = milesSingle[j] + milesDouble[j] + milesTriple[j] + milesQuad[j] + milesPent[j] + milesSex[j];
etc.
It should use javascript FOR to loop through each record and test to see if they sum to the same thing.
In Firefox and IE this is working properly; the fields sum properly into "sumByType" and "sumByTrack". You can see below I added a little alert to figure out what was going wrong:
alert(sumByType + " " + j + " " + recCnt + " " + milesSurf[j] + " " + milesElev[j] + " " + milesUnder[j]);
In Chrome, that alert tells me that the components of "sumByType" and "sumByTrack" (the various "milesXXXXX" variables) are undefined.
My question is: Why in Chrome is this not working properly, when in IE and FFox it is? Any ideas?
Full function code below:
function submitCheck(formy, recCnt) {
//2/10/03: added milesQuad
//---------------checks Q#4 that Line Mileage by type is the same as by track
var milesElev = new Array();
var milesSurf = new Array();
var milesUnder = new Array();
var milesSingle = new Array();
var milesDouble = new Array();
var milesTriple = new Array();
var milesQuad = new Array();
var milesPent = new Array();
var milesSex = new Array();
var sumByType = 0;
var milesLineTrack = new Array(); //this is for Q5 to compare it to mileage by trackage
var j = 0; var sumByTrack = 0; var liney; var yrOp;
//var str = "document.frm.milesElev" + j;
//alert(str.value);
for (var i in document.frm) {
if (i.substring(0, i.length - 1) == "milesElev") {
milesElev[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSurf") {
milesSurf[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesUnder") {
milesUnder[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSingle") {
milesSingle[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesDouble") {
milesDouble[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesTriple") {
milesTriple[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesQuad") {
milesQuad[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesPent") {
milesPent[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSex") {
milesSex[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length -1) == "milesLineTrack") {
milesLineTrack[parseInt(i.substring(i.length-1, i.length))] = document.frm[i].value; } //12/13/02 used to be parseFloat(document.frm[i].value)
if (i.substring(0,5)=="Lines") {
liney = document.frm[i].value;
if (parseInt(liney)<1 || isNaN(liney)) {
alert("Each mode must have at least 1 line. Please correct the value in question #2.");
document.frm[i].select(); return false; }}
if (i.substring(0,8)=="yearOpen") {
yrOp = document.frm[i].value;
if (parseInt(yrOp)<1825 || isNaN(yrOp)) {
alert("Please enter a year after 1825 for question #3");
document.frm[i].select(); return false; }
}
}
for (var j=0; j<recCnt; j++) {
sumByType = milesSurf[j] + milesElev[j] + milesUnder[j];
sumByTrack = milesSingle[j] + milesDouble[j] + milesTriple[j] + milesQuad[j] + milesPent[j] + milesSex[j];
//---------------to round sumByTrack and sumByType from a long decimal to a single decimal place, like frm 7.89999998 to 7.9.
sumByTrack = sumByTrack * 10;
if (sumByTrack != parseInt(sumByTrack)) {
if (sumByTrack - parseInt(sumByTrack) >= .5) {
//round up
sumByTrack = parseInt(sumByTrack) + 1; }
else { //truncate
sumByTrack = parseInt(sumByTrack); }}
sumByTrack = sumByTrack / 10;
sumByType = sumByType * 10;
if (sumByType != parseInt(sumByType)) {
if (sumByType - parseInt(sumByType) >= .5) {
//round up
sumByType = parseInt(sumByType) + 1; }
else { //truncate
sumByType = parseInt(sumByType); }}
sumByType = sumByType / 10;
//-------------end of rounding ---------------------------
if (sumByType != sumByTrack) {
if (isNaN(sumByType)) {
sumByType = "(sum of 4.a., b., and c.) "; }
else {
sumByType = "of " + sumByType; }
if (isNaN(sumByTrack)) {
sumByTrack = "(sum of 4.d., e., f., g., h., and i.) "; }
else {
sumByTrack = "of " + sumByTrack; }
alert("For #4, the 'End-to-End Mileage By Type' " + sumByType + " must equal the 'End-to-end Mileage By Trackage' " + sumByTrack + ".");
alert(sumByType + " " + j + " " + recCnt + " " + milesSurf[j] + " " + milesElev[j] + " " + milesUnder[j]);
return false;
}
//alert (milesLineTrack[j] + " " + milesSingle[j] + " " + 2*milesDouble[j] + " " + 3*milesTriple[j] + " " + 4*milesQuad[j] + " " + 5*milesPent[j] + " " + 6*milesSex[j]);
var singDoubTrip = (milesSingle[j] + 2*milesDouble[j] + 3*milesTriple[j] + 4*milesQuad[j] + 5*milesPent[j] + 6*milesSex[j])
//----------round singDoubTrip to one digit after the decimal point (like from 6.000000001 to 6.0)
singDoubTrip = singDoubTrip * 10;
if (singDoubTrip != parseInt(singDoubTrip)) {
if (singDoubTrip - parseInt(singDoubTrip) >= .5) {
//round up
singDoubTrip = parseInt(singDoubTrip) + 1; }
else { //truncate
singDoubTrip = parseInt(singDoubTrip); }}
singDoubTrip = singDoubTrip / 10;
//----------end round singDoubTrip-----------------------------------------
if (parseFloat(milesLineTrack[j]) != singDoubTrip) {
//var mlt = milesLineTrack[j];
//if isNaN(milesLineTrack[j]) { mlt =
alert("For column #" + (j+1) + ", the mainline passenger track mileage of " + milesLineTrack[j] + " must equal the single track plus 2 times the double track plus 3 times the triple track plus 4 times the quadruple track plus 5 times the quintuple track plus 6 times the sextuple track, which is " + singDoubTrip + ".");
return false;
}
}
//---------------------end of checking Q#4----------------
//return false;
}
I think for (var i in document.frm) is the problem. You should not enumerate a form element, there will be plenty of unexpected properties - see Why is using "for...in" with array iteration a bad idea?, which is especially true for array-like objects. I can't believe this works properly in FF :-)
Use this:
var ele = document.frm.elements; // or even better document.getElementById("frm")
for (var i=0; i<ele.length; i++) {
// use ele[i] to access the element,
// and ele[i].name instead of i where you need the name
}
Also, you should favour a loop over those gazillion of if-statements.