I can't figure this out I keep getting stuck in a loop. I don't know if I have my calculation or if statements in the right areas, please I could use some help. My output is like a end of day report. I could really use the help.
<script type="text/javascript">
<!--
// assignments
var cost, nachosCounter, moneyCollected, nachosRate, corndogRate, hotdogRate;
var hamAccum, hotdogAccum, corndogAccum, nachosAccum, hamburgerRate;
var beginDay, orderType, hamCounter, hotdogCounter, corndogCounter;
var totalHotdog, totalNachos, totalCorndog, totalHamburger, moneyCollected;
var hamburgerRate = 4;
var hotDogRate = 2;
var cornDogRate = 3;
var nachosRate = 5;
var hamCounter = 0;
var hotdogCounter = 0;
var corndogCounter = 0;
var nachosCounter = 0;
var beginDay = "yes"
//initalizing loop
beginDay = "yes"
//start loop
while (beginDay == "yes")
{
orderType = prompt("hamburger, hotdog, corndog, nachos", "");
if (orderType == "hamburger")
{
hamCounter = hamCounter + 1;
if (hamCounter == 1)
{
hamAccum = "<br>The total number of hamburgers purchased: " + hamCounter;
}
else
{
hamAccum = hamAccum + "<br>" + hamCounter;
}
}
else if (orderType == "hotdog")
{
hotdogCounter = hotdogCounter + 1;
if (hotdogCounter == 1)
{
hotdogAccum = "The total number of hotdog purchased:<br>" + hotdogCounter;
}
else
{
hotdogAccum = hotdogAccum + "<br>" + hotdogCounter;
}
}
if (orderType == "corndog")
{
corndogCounter = corndogCounter + 1;
if (corndogCounter == 1)
{
corndogAccum = "<br>The total number of corndogs purchased: <br>" + corndogCounter;
}
else
{
corndogAccum = corndogAccum + "<br>" + corndogCounter;
}
}
if (orderType == "nachos")
{
nachosCounter = nachosCounter + 1;
if (nachosCounter == 1)
{
nachosAccum = "<br>The total number of nachos purchased: <br>" + nachosCounter;
}
else
{
nachosAccum = nachosAccum + "<br>" + nachosCounter;
}
}
totalHotdog = hotdogCounter*hotDogRate;
totalHamburger = hamCounter*hamburgerRate;
totalCorndog = corndogCounter*cornDogRate;
totalNachos = nachosCounter*nachosRate;
moneyCollected = totalNachos+totalCorndog+totalHamburger+totalHotdog;
beginDay = prompt("More to add?", "yes");
}
//output
document.write(hotdogAccum);
document.write(hamAccum);
document.write(corndogAccum);
document.write(nachosAccum);
document.write("<br>The total dollar amount for hotdog: $ " + totalHotdog);
document.write("<br>The total dollar amount for hamburger: $ " + totalHamburger);
document.write("<br>The total dollar amount for corndogs: $" + totalCorndog);
document.write("<br>The total dollar amount for nachos: $" + totalNachos);
document.write("The total amount of money collected: $" + moneyCollected);
// -->
</script>
Related
working on some word problems for my intro class and my html keeps getting stuck in a loop in the alert section of my code. once it goes in there it doesn't come back out no matter if I am inputting correctly. this is a beginner class so we have only just gotten into loops and switches so please keep it basic. thanks in advance!
var custOwed, numCust, dayTotal;
var woodTotal, alumTotal, steelTotal;
var rate;
var woodCount = 0;
var alumCount = 0;
var steelCount = 0;
var woodAccum = 0;
var alumAccum = 0;
var steelAccum = 0;
var anotherOrder = "yes";
var woodRate = 10;
var alumRate = 15;
var steelRate = 25;
var errorFlag = 0;
anotherOrder = prompt("Another Order", "yes or no");
while (anotherOrder == "yes") {
poleType = prompt("What type of pole would you like today?", "wood, aluminum, or steel");
numFeet = prompt("How many feet?", "10");
numFeet = parseInt(numFeet);
switch (poleType) {
case "wood":
woodCount = woodCount + 1;
woodAccum = woodAccum + numFeet;
rate = woodRate;
break;
case "aluminum":
alumCount = alumCount + 1;
alumAccum = alumAccum + numFeet;
rate = alumRate;
break;
case "steel":
steelCount = steelCount + 1;
steelAccum = steelAccum + numFeet;
rate = steelRate;
break;
default:
errorFlag = 1;
break;
}
if (errorFlag == 1) {
alert("You typed " + poleType + " the only choices were wood, aluminum, or steel");
anotherOrder = "yes";
} else {
custOwed = numFeet * rate;
alert("You Owe" + custOwed);
anotherOrder = prompt("Another Customer?", "yes or no");
}
}
numCust = woodCount + alumCount + steelCount;
woodTotal = woodAccum * woodRate;
alumTotal = alumAccum * alumRate
steelTotal = steelAccum * steelRate
dayTotal = woodTotal + alumTotal + steelTotal;
document.write("Number of Customers: " + numCust);
document.write("<br>Wood Customers: " + woodCount);
document.write("<br>Total Feet of Wood: " + woodAccum);
document.write("<br>Total owed of Wood: $" + woodTotal.toFixed(2));
document.write("<br>Aluminum Customers: " + alumCount);
document.write("<br>Total Feet of Aluminum: " + alumAccum);
document.write("<br>Total owed of Aluminum: $" + alumTotal.toFixed(2));
document.write("<br>Steel Customers: " + alumCount);
document.write("<br>Total Feet of Steel: " + alumAccum);
document.write("<br>Total owed of Steel: $" + alumTotal.toFixed(2));
document.write("<br>Total owed from the day: $" + dayTotal.toFixed(2));
I am trying to display an array of test scores and above them, the average of those scores. Here is the code I am using:
var clickDisplayResults = function () {
$("results").value = "";
function calculate(scores) {
var i = 0, sum = 0, len = scores.length;
while (i < len) {
sum = sum + scores[i++];
};
return sum / len;
};
var average = calculate(scores);
$("results").value = "The average score is: " + parseInt(average) + "\n";
$("results").value += "High Score: " + Math.max.apply(null, scores) + "\n";
$("results").value += "Low Score: " + Math.min.apply(null, scores) + "\n" + "\n";
for (var i = 0; i < names.length; i++) {
$("results").value += names[i] + ", " + scores[i] + "\n";
};
When I do this, however, I get an average in a ridiculous range after adding a new score.
Here is the add score code:
var clickAddScore = function () {
if ( $("name").value == "" || $("score").value < 0 || $("score").value > 100 || isNaN($("score").value) ) {
alert("Please enter a valid name and score");
$("name").value = "";
$("score").value = "";
return false;
};
else {
names[names.length] = $("name").value;
scores[scores.length] = $("score").value;
$("name").value = "";
$("score").value = "";
};
};
Any advice would be appreciated.
You are working with a string and treating it like a number
console.log("100" + 100);
You need to convert the string to a number. You can use parseInt, parseFloat, Number, or Unary plus.
Your code is a bit inefficient since you keep accessing the DOM for the value so declare some variables. And your else statement was wrong.
var clickAddScore = function() {
var studentName = $("name").value.trim();
var score = Number($("score").value);
if (studentName == "" || score < 0 || score > 100 || isNaN(score)) {
alert("Please enter a valid name and score");
} else {
names.push(studentName);
scores.push(score);
}
$("name").value = "";
$("score").value = "";
}
I am new to Javascript. Below is simple program where I am trying to display elements from array that I have created. It does not work. Can anybody please let me know what I am doing wrong?
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Javascript Excercises - Functions</title>
<script>
function findPrimeFactors(){
var primefacts = [];
var primefacs;
var unum = prompt("Please enter a positive number");
var i = 2;
var num = parseInt(unum);
if (num > 0) {
while (num >= i){
if (num % i == 0){
primefacts.push(i);
num = num / i;
console.log("Prime factor: " + i + " New num: " + num + " Array length: " + primefacts.length + " Last array element: " + primefacts[primefacts.length-1]);
}
else {
i += 1;
}
};
if (primefacts.length = 0) {
document.write("No prime factors other than 1 for this number.");
}
else {
primefacs = primefacts.join();
console.log("Prime factors: " + primefacts[0] + ", " + primefacts[1] + ", " + primefacts[2]);
document.write("The prime factor for " + unum + " are : " + primefacs);
}
}
}
</script>
</head>
<body>
<button onclick="findPrimeFactors()">Click to proceed</button>
</body>
replace:-
if (primefacts.length = 0) {
with
if (primefacts.length == 0) {
you are setting the length to 0 instead of comparing.
function findPrimeFactors() {
var primefacts = [];
var primefacs;
var unum = prompt("Please enter a positive number");
var i = 2;
var num = parseInt(unum);
if (num > 0) {
while (num >= i) {
if (num % i == 0) {
primefacts.push(i);
num = num / i;
console.log("Prime factor: " + i + " New num: " + num + " Array length: " + primefacts.length + " Last array element: " + primefacts[primefacts.length - 1]);
} else {
i += 1;
}
};
if (primefacts.length == 0) {
document.write("No prime factors other than 1 for this number.");
} else {
primefacs = primefacts.join();
console.log("Prime factors: " + primefacts[0] + ", " + primefacts[1] + ", " + primefacts[2]);
document.write("The prime factor for " + unum + " are : " + primefacs);
}
}
}
<button onclick="findPrimeFactors()">Click to proceed</button>
So, i'm adding 2 characters 4 levels together (hp, attack, strength and defense) and then comparing them. However I am having a problem. when the numbers are added together they're added together as a string so it outputs as follows. 9060951/99709940 instead of 246 (90+60+95+1)/308 (99+70+99+40). Here is what I am doing.
function calculate(player1, player2) {
var total1 = player1.getTotal();
var total2 = player2.getTotal();
var differencePercentage;
if(total1 > total2) {
differencePercentage = total2 + "/" + total1 + " = " + (total2/total1);
} else {
differencePercentage = total1 + "/" + total2 + " = " + (total1/total2);
}
var percentage = differencePercentage;
return percentage;
}
function Player(hp, attack, strength, defense) {
this.hp = parseInt(hp);
this.attack = parseInt(attack);
this.strength = parseInt(strength);
this.defense = parseInt(defense);
this.getTotal = function() {
var total = 0;
total = hp + attack + strength + defense;
return total;
}
}
Why is this happening?
You are parsing the Ints into this.hp, this.attack etc. in your Player function but not into the getTotal function
Try this
this.getTotal = function() {
var total = 0;
total = this.hp + this.attack + this.strength + this.defense;
return total;
}
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.