JavaScript - Loops With Functions
I created a For Loop and counter starts at 0, then increase in increments of 1
after each iteration of loop i run a command 1( add html code such as Code: <td>named (part)</td> <td class= 'num'>votes</td> Then create variable of named percent use totalV for value of sum parameter then i add html code of Code: <td class='num'>(percent%(</td> then i add a function named createBar(0 using race[0], name1, party1, and votes1 in parameter values this is my coding Code: for (var i=0; i < name.length; i++) { document.write("<tr>"); document.write("<td>" name[i] + "(" + party[i] + ")</td>"); document.write("<td class='num'>" + votes[i] + "</td>"); var percent=calcPercent(votes[i], totalV) document.write("<td class='num'>(" + percent +"%)</td>"); createBar(party[i],percent) document.write("</tr>"); } document.write("</table>"); } </script> </head> so any improvements or what i am missing in my functions. Similar TutorialsI've now got to form an average of snowfall inputs, taken from looped prompts, however I'm not allowed to use arrays or functions... Almost every example I see uses arrays, such as this one he http://www.codingforums.com/showthread.php?t=4313 Is it possible to not use arrays to form the average? Please describe how to do this in general terms, as was highlighted in that link ^^^ I want to learn, not copy, although one can be derived from the other... What I haveso far, assume all vars have been announced. Code: for (var d=1; d<=numofinputs; d=d+1) { input = prompt("Enter a data input" + d) } Is it possible I'm attempting this in too general a manner? ie, running before I can walk. Hello, Problem 1: I have a function and it sets a value to a certain number according to the input. However, I don't want the function to print out the value to the screen, but instead temporarily save it for me to use throughout the whole script. I am a newbie and please help me. For example, I make this code: function add1(x) { var x = x + 1 return x; } and I call the function: add1(0); document.write("value = " + x + "<BR>"); Whenever I do this, document.write doesn't print out value = 1, it doesn't even print anything except for the headers, etc. Is there anyway to set the var x to be a value valid throughout the whole script instead of just the function itself? I really need help on this, thanks. Problem 2: I want to get a code working. Basically, I use a ram to "ram the gate". I set the damage done each turn, and the Gate's Health too. So for example, my ram's damage is 10 and the gate's health is 200. It would take 20 times to totally breach the gates(i.e., for gate health to become 0). When I use the following code, the total damage is the same throughout the whole looping until the gatehealth reaches 0 which makes it boring, is there anyway to modify or improve the script such that when I loop, the MiscDamage would be different for all the turns? thanks! Once again I apologize for asking such a noob-ish and very strange.... question. Quote: <script language="JavaScript" type="text/javascript"> <!-- // Begin function RamGates(Ram, Attack, Gate) { //introducing variables to be used var BaseDamage = 0; var FullDamage = 0; var MiscDamage = 0; var TotalDamage = 0; var GateHealth = 0; switch (Ram) { //ignore this part just comparing ram types case "Explosive": BaseDamage="10"; break; case "Wooden": BaseDamage="20"; break; case "Steel": BaseDamage="30"; break; case "", "?": default: BaseDamage="Failed to recognize Ram"; } switch (Attack) { //ignore this just comparing attack values case 0: FullDamage = BaseDamage; break; case 1: FullDamage = (BaseDamage*2)-8; break; case 2: FullDamage = (BaseDamage*2)-6; break; case 3: FullDamage = (BaseDamage*2)-4; break; case 4: FullDamage = (BaseDamage*2)-2; break; case 5: FullDamage = BaseDamage*2; break; case "", "?": default: FullDamage="Failed to recognize Attack"; } switch (Ram) { //this part is what i need help on, i need the loop function to keep using this to generate different "lucky damages" each time to make it interesting, i.e., first ram = 11 second ram = 16 third ram = 14 and so on..... case "Explosive": MiscDamage = Math.floor(Math.random()*21+10); break; case "Wooden": MiscDamage = Math.floor(Math.random()*6+0); break; case "Steel": MiscDamage = Math.floor(Math.random()*11+5); break; case "", "?": default: MiscDamage="Failed to recognize Ram"; } switch (Gate) { //ignore this part just comparing gate types to generate gate health case "Wooden": GateHealth = 50; break; case "Brick": GateHealth = 75; break; case "Small Stone": GateHealth = 90; break; case "Large Stone": GateHealth = 120; break; case "Granite": GateHealth = 140; break; case "Iron": GateHealth = 175; break; case "R Iron": GateHealth = 190; break; case "Thick Iron": GateHealth = 210; break; case "Steel": GateHealth = 230; break; case "R Steel": GateHealth = 250; break; case "Thick Steel": GateHealth = 275; break; case "Steel Iron Mix": GateHealth = 280; break; case "Thick Steel Iron Mix": GateHealth = 300; break; case "Strong Ruby Steel Mix": GateHealth = 400; break; case "Strong Sapphire Steel Mix": GateHealth = 450; break; case "R Thick Large Diamond Steel Mix": GateHealth = 500; break; case "", "?": default: GateHealth = "Failed to recognize Gate"; } TotalDamage = FullDamage + MiscDamage; with (document) { write ("Soldiers, " + "RAM THE GATES!" + "<BR>"); } while (GateHealth >= 0) //loops until gate health is lower than 0 { //need help! how to make it such that the loop will rerun the switching of ram for generating random misc(lucky) damages document.write ("Lucky Damage done = " + MiscDamage + "<BR>"); document.write ("Total Damage done = " + TotalDamage + "<BR>"); var GateHealth = GateHealth - TotalDamage document.write("Current GateHealth = " + GateHealth + "<BR>"); } } RamGates("Explosive", 5, "R Thick Large Diamond Steel Mix"); //function calling // End --> </script> I want to learn javascript and I found codecademy.com which seems like a great way to learn the language. Before the first lesson it says Quote: You should be comfortable with loops, if statements, functions, and objects before attempting this course. Can someone explain what these are or point me in the direction where I can find the answers? I tried searching with google, but I havent found anything that clearly states what exactly the loop, object, etc. is. Hey all, I am confused about the true difference between the two below examples. Code: first example: // Demonstrating a problem with closures and loops var myArray = [“Apple”, “Car”, “Tree”, “Castle”]; var closureArray = new Array(); // Loop through myArray and create a closure for each that outputs that item for (var i = 0; i < myArray.length; i++) { var theItem = myArray[i]; closureArray[i] = function() { document.write(theItem + “ < br / > ”); } } // Loop through the closures and execute each one. for (var i = 0; i < closureArray.length; i++) { closureArray[i](); } Here we iterate through the length of myArray, assigning the current index of myArray to theItem variable. We declare closureArray 4 times as an anonymous function. The anonymous function in turn declares the predefined write() function, which is passed parameters. Since write() is in closureArray() a closure is created??? During each iteration, theItem is reassigned its value. The four closures reference this value. Since they reference this same value and since this value is reassigned ultimately to the value of the fourth index position, tHe time we execute closureArray later on, all four closures output the same string. This is because all four closures are within the same scope "the same environment" and therefore are referencing the same local variable, which has changed. I have a couple of problems with this example: 1) I thought a closure is a function that is returned - the inner function is not returned above. 2) theItem is not even a local variable of the parent function (closureArray) - I thought in order for a closure to work, the inner function only accesses the local variables of the outer function, but in this case the local variable is defined OUTSIDE of the parent function. 3) The guy says the "the four closures are sharing the same environment." The thing is even in the second example, they are sharing the same environment. Second example: Code: // A correct use of closures within loops var myArray = [“Apple”, “Car”, “Tree”, “Castle”]; var closureArray = new Array(); function writeItem(word) { return function() { document.write(word + “ < br / > ”); } } // Loop through myArray and create a closure for each that outputs that item for (var i = 0; i < myArray.length; i++) { var theItem = myArray[i]; closureArray[i] = writeItem(theItem); } // Loop through the closures and execute each one. for (var i = 0; i < closureArray.length; i++) { closureArray[i](); } Here we iterate over the length of myArray (4 times), assigning the index of myArray to theItem variable. We also return a function reference to the closureArray during each iteration (closureArray[i]), where i is index number so we assign 4 functon references. So when we iterate through myArray, we immediatelly call the writeItem() fucntion passing an argument of theItem at its current value. This returns a child anonymous function and when that child function is called, it will execute a block that calls the predefined write() method. We assign that returned anonymous function to the variable closureArray. Hence, closureArray holds a reference to that anonymous function. So closureArray during each iteration holds a reference to the anonymous function and we later call closureArray, which in turn calls the anonymous function, therefore calling the predefined write() function to output the local variable of the parent function. This outputs each distinct index of myArray. QUESTION: This is because since we created the closure, when we call writeItem, passing theItem argument, since theItem is a local variable of the parent function of the closure, it is never destroyed when we later call closureArray (the reference to the child anonymous function)? Yet weren't we using a closure in the first example as well? So whey wasn't those variables preserved? I don't think it has anything to do with assigning a returned anonymous function to closureArray. Even though an anonymous function creates a new memory position in the javascript engine, therefore not overwriting the other function references we create during the iteration, it's still referring to a local variable declared outside the reference. So if it's about the closure retaining value of parent's local variable even after exiting the parent function allowing for the current indexes to be preserved, then why did the closure in the first example fail to retain each index? Thanks for response Hi, I have written a number of functions designed to return frequency data on 1000 randomly chosen numbers using different math functions for the rounding. I would like to include all of these functions within the wrapper of another function so that only one call is needed to get returns from all of the 'inner' functions. However, while each of the functions works in isolation, the moment I wrap them in another function they stop working. The following code is one of the functions 'frequencyWrapperOne' that has been wrapped in the function 'testWrapper'. A call to testWrapper does nothing. Can anyone see what I'm doing wrong? Code: function testWrapper() { function frequencyWrapperOne() { var numberArrayOne = new Array(0,0,0); for (var i = 0; i < 1000; i = i + 1) { var chosenNumber = Math.floor(Math.random() * 3); if (chosenNumber == 0) { numberArrayOne[0] = numberArrayOne[0] + 1; } if (chosenNumber == 1) { numberArrayOne[1] = numberArrayOne[1] + 1; } if (chosenNumber == 2) { numberArrayOne[2] = numberArrayOne[2] + 1; } } return window.alert(numberArrayOne.join(',')); } } testWrapper(); Thanks. Is there a way to activate a function from another function? It has to be in the script tag, it can't be in the HTML section. Can I use something similar to this following code? If not, can anyone give me some help? I have tried to do it various ways, and have looked it up a few times, but to no avail. Can I use something similar to this following code? If not, can anyone give me some help? if (condition) {activate functionname();} Any help I can get would be appreciated. Thanks a lot to anyone who can help. Ok here is what I have so far, my ending part of my Call Function I think is ok. for my main function. I think I misplaced the { and } I will show you all the codes I have for my main function this is what I have I think I did misplace something but I can not pin point where that one small things should be Code: unction showResults(race,name,party,votes) { // script element to display the results of a particular race var totalV = totalVotes(votes); document.write("<h2>" + race + "</h2>"); document.write("<table cellspacing='0'>"); document.write("<tr>"); document.write("<th>Candidate</th>"); document.write("<th class ='num'>Votes</th>"); document.write("<th class='num'>%</th>"); document.write("</tr>"); } for (var i=0; i < name.length; i++) { document.write("<tr>"); document.write("<td>" name[i] + "(" + party[i] + ")</td>"); document.write("td class='num'>" + votes[i] + "</td>"); var percent=calcPercent(votes[i], totalV) document.write("<td class='num'>(" + percent +"%)</td>"); createBar(party[i],percent) document.write("</tr>"); } document.write("</table>"); } </script> Just wondering if i misplaced any ; or { or } anywhere suggestions? Here is my call function Code: <script type="text/javascript"> showResults(race[0],name1,party1,votes1); showResults(race[1],name2,party2,votes2); showResults(race[2],name3,party3,votes3); showResults(race[3],name4,party4,votes4); showResults(race[4],name5,party5,votes5); </script> I been going over this, I can not seem to figure out what { i might be missing? Thanks Hello, i am new here however my knowledge is not that limited like that one guy wolf who oldMaster was helping with i read the RULES and his thread lol so my question is, i have made a for loop and in side the for loop i wrote document.write(<td>date</td>"<td class = 'amt'>amount</td>); where date, amount, firstName, and lastName, are the values of the date, amount, firstName, and lastName arrays for the index indicated by the current value of the for loop counter varible so questions : i have spent the past 3 days looking online for the correct answer document.write(<td>date</td>"<td class = 'amt'>amount</td>); ? HTML FILE Code: <title>The Lighthouse</title> <link href="lhouse.css" rel="stylesheet" type="text/css" /> <script type = "text/javascript" src = "list.js"></script> <!-- caling the external file --> <script type ="text/javascript"> function amountTotal(){ //i dont think we need an array made because we have called the external file called list.js which holds the arrays //sets the variable to 0 var total = 0; //new Array("firstName", "lastName", "street", "city", "state", "zip", "amount", "date"); //that loops through all the values in the amount array, at each point in the loop add the current value of the array item to the value of the total variable for(var i = 0; i < amount.length; i++) { total = total + amount[i]; }//enf forloop //i must return the sum of all the values in the amount array return total; }//end of function total </script> </head> <body> <div id="title"> <img src="logo.jpg" alt="The Lighthouse" /> The Lighthouse<br /> 543 Oak Street<br /> Owensboro, KY 42302<br/> (270) 555-7511 </div> <div id="data_list"> <!--//creates a new script --> <script type = "text/javascript"> document.write("<table border='1' rules='rows' cellspacing='0'>"); document.write("<tr>"); document.write("<th>Date</th><th>Amount</th><th>First Name</th>"); document.write("<th>Last Name</th><th>Address</th>"); document.write("</tr>"); document.write("</table>"); for(var i = 0; i < date.length; i++) { if(i % 2 ) document.write("<tr>"); else document.write("<tr class='yellowrow'>"); document.write("<td>"date"</td>"<td class = 'amt'>amount"</td>"); }//end for </script> </div> <div id="totals"> <!--//this creates a script --> <script type = "text/javascript"> //this is how to print a table to the screen only when html is inside a script document.write( <table border='1' cellspacing='1'> <tr> <th id ='sumTitle' colspan='2'> Summary </th> </tr> <tr> <th>Contributors</th> <th>contributions</th> </tr> <tr> <th>Amount</th> <td>$total</td> </tr> </table>); </script> </div> </body> </html> THIS IS THE ARRAY LIST WHICH IS THE EXTERNAL FILE Code: firstName = new Array(); lastName = new Array(); street = new Array(); city = new Array(); state= new Array(); zip = new Array(); amount = new Array(); date = new Array() firstName[0]="Nina"; lastName[0]="Largent"; street[0]="88 Regal Lane"; city[0]="Williamsburg"; state[0]="KY"; zip[0]="40769"; amount[0]=125; date[0]="2011-09-18"; firstName[1]="Mike"; lastName[1]="Hunt"; street[1]="Da404 Barrow Street"; city[1]="London"; state[1]="KY"; zip[1]="40742"; amount[1]=75; date[1]="2011-09-18"; firstName[2]="Monica"; lastName[2]="Lang"; street[2]="743 Stawlings Drive"; city[2]="Danville"; state[2]="KY"; zip[2]="40423"; amount[2]=50; date[2]="2011-09-16"; firstName[3]="William"; lastName[3]="Mcknight"; street[3]="102 Maple Lane"; city[3]="Danville"; state[3]="KY"; zip[3]="40423"; amount[3]=150; date[3]="2011-09-15"; firstName[4]="Latrina"; lastName[4]="Hults"; street[4]="750 Whitehall Road"; city[4]="London"; state[4]="KY"; zip[4]="40742"; amount[4]=250; date[4]="2011-09-14"; firstName[5]="Danny"; lastName[5]="Shamblin"; street[5]="123 Smith Drive"; city[5]="Owensboro"; state[5]="KY"; zip[5]="42303"; amount[5]=50; date[5]="2011-09-13"; firstName[6]="Tina"; lastName[6]="Ammons"; street[6]="888 Evans Way"; city[6]="Williamsburg"; state[6]="KY"; zip[6]="40769"; amount[6]=50; date[6]="2011-09-13"; firstName[7]="Joanne"; lastName[7]="Fine"; street[7]="210 Bowling Terrace"; city[7]="Williamsburg"; state[7]="KY"; zip[7]="40769"; amount[7]=125; date[7]="2011-09-11"; firstName[8]="Charlotte"; lastName[8]="Foulk"; street[8]="109 South Road"; city[8]="Danville"; state[8]="KY"; zip[8]="40423"; amount[8]=50; date[8]="2011-09-10"; firstName[9]="Candice"; lastName[9]="Alfaro"; street[9]="108 Atwood Avenue"; city[9]="Owensboro"; state[9]="KY"; zip[9]="42303"; amount[9]=400; date[9]="2011-09-08"; firstName[10]="Kristi"; lastName[10]="Laine"; street[10]="512 North Lane"; city[10]="Williamsburg"; state[10]="KY"; zip[10]="40769"; amount[10]=225; date[10]="2011-09-08"; firstName[11]="Elisabeth"; lastName[11]="Carbone"; street[11]="381 Main Street"; city[11]="London"; state[11]="KY"; zip[11]="40742"; amount[11]=200; date[11]="2011-09-07"; firstName[12]="James"; lastName[12]="Larsen"; street[12]="212 Rawlings Way"; city[12]="Jackson"; state[12]="KY"; zip[12]="41339"; amount[12]=125; date[12]="2011-09-07"; firstName[13]="Ralph"; lastName[13]="Thornton"; street[13]="444 Smith Drive"; city[13]="Owensboro"; state[13]="KY"; zip[13]="42303"; amount[13]=100; date[13]="2011-09-07"; firstName[14]="Robin"; lastName[14]="Witt"; street[14]="78 Norland Pines"; city[14]="London"; state[14]="KY"; zip[14]="40742"; amount[14]=75; date[14]="2011-09-07"; firstName[15]="Alex"; lastName[15]="Ruiz"; street[15]="102 Sunset Road"; city[15]="Jackson"; state[15]="KY"; zip[15]="41339"; amount[15]=50; date[15]="2011-09-06"; firstName[16]="Callie"; lastName[16]="Rudy"; street[16]="3 Sunset Road"; city[16]="Jackson"; state[16]="KY"; zip[16]="41339"; amount[16]=50; date[16]="2011-09-06"; firstName[17]="Michael"; lastName[17]="Harrell"; street[17]="125 Sunset Road"; city[17]="Jackson"; state[17]="KY"; zip[17]="41339"; amount[17]=50; date[17]="2011-09-06"; firstName[18]="Edgar"; lastName[18]="Morales"; street[18]="387 North Lane"; city[18]="Williamsburg"; state[18]="KY"; zip[18]="40769"; amount[18]=250; date[18]="2011-09-05"; firstName[19]="Arlene"; lastName[19]="Lutz"; street[19]="7888 Clear View Drive"; city[19]="Danville"; state[19]="KY"; zip[19]="40423"; amount[19]=75; date[19]="2011-09-05"; firstName[20]="Earl"; lastName[20]="Holmes"; street[20]="1001 Rawlings Way"; city[20]="Jackson"; state[20]="KY"; zip[20]="41339"; amount[20]=500; date[20]="2011-09-04"; firstName[21]="Bernice"; lastName[21]="Drew"; street[21]="25 Main Street"; city[21]="London"; state[21]="KY"; zip[21]="40742"; amount[21]=150; date[21]="2011-09-04"; firstName[22]="Patrick"; lastName[22]="Granier"; street[22]="100 Atwood Avenue"; city[22]="Owensboro"; state[22]="KY"; zip[22]="42303"; amount[22]=75; date[22]="2011-09-03"; firstName[23]="Henry"; lastName[23]="Bailey"; street[23]="37 East Maple Street"; city[23]="Danville"; state[23]="KY"; zip[23]="40423"; amount[23]=50; date[23]="2011-09-03"; firstName[24]="Ginny"; lastName[24]="Rainey"; street[24]="657 Dawson Lane"; city[24]="Danville"; state[24]="KY"; zip[24]="40423"; amount[24]=50; date[24]="2011-09-03"; firstName[25]="Ginny"; lastName[25]="Rainey"; street[25]="657 Dawson Lane"; city[25]="Danville"; state[25]="KY"; zip[25]="40423"; amount[25]=75; date[25]="2011-09-03"; firstName[26]="Basilia"; lastName[26]="Lu"; street[26]="851 Flad Court"; city[26]="Jackson"; state[26]="KY"; zip[26]="41339"; amount[26]=500; date[26]="2011-09-02"; firstName[27]="Livia"; lastName[27]="Mckinnon"; street[27]="557 Ivy Avenue"; city[27]="Jackson"; state[27]="KY"; zip[27]="41339"; amount[27]=50; date[27]="2011-08-31"; firstName[28]="Kris"; lastName[28]="Levesque"; street[28]="542 Upton Avenue"; city[28]="Owensboro"; state[28]="KY"; zip[28]="42303"; amount[28]=100; date[28]="2011-08-31"; firstName[29]="Lynwood"; lastName[29]="Ingersoll"; street[29]="723 Jackson Avenue"; city[29]="Owensboro"; state[29]="KY"; zip[29]="42303"; amount[29]=500; date[29]="2011-08-30"; firstName[30]="Petronila"; lastName[30]="Damico"; street[30]="44 Stewart Street"; city[30]="London"; state[30]="KY"; zip[30]="40742"; amount[30]=250; date[30]="2011-08-30"; firstName[31]="Hugh"; lastName[31]="Warren"; street[31]="585 Lindon Court"; city[31]="Williamsburg"; state[31]="KY"; zip[31]="40769"; amount[31]=50; date[31]="2011-08-28"; firstName[32]="Tom"; lastName[32]="Thomas"; street[32]="Rigel Avenue"; city[32]="London"; state[32]="KY"; zip[32]="40742"; amount[32]=100; date[32]="2011-08-27"; firstName[33]="Steve"; lastName[33]="Bones"; street[33]="900 Lawton Street"; city[33]="Williamsburg"; state[33]="KY"; zip[33]="40769"; amount[33]=50; date[33]="2011-08-25"; firstName[34]="Jeri"; lastName[34]="White"; street[34]="Hawkes Lane"; city[34]="Owensboro"; state[34]="KY"; zip[34]="42303"; amount[34]=150; date[34]="2011-08-25"; Hey Guys! I've previously done HTML, but now started to learn some aspects of Javascript but getting rather confused with Loops! I've done a some coding for the Loop question (probably doesn't make sense) but I was wondering if you could help me out? I'm about as confused as a cow on a Astro Turf so my code may look terrible! - For this question you will: Draw a flow chart and write a javascript function which will use a for loop and allow the user to enter the details for four students when the program is run and display the average. Assume that they equal weighting. Hint: Javascript may assume that the value received from a prompt is a string so use parseInt() to make sure the number is an integer. Here is my code: (I'm using Aptana) Code: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <meta http-equiv="Content-Type" content="text/javascript; charset=utf-8"/> <title>Average Marks</title> <!-- Date: 2011-10-27 --> <head> <script type="text/javascript"> function marks () { var mark1 = 10; var mark2 = 25; var mark3 = 50; for(var mark1 = 10; mark1<20; mark1++) (var mark2 = 25; mark2<50; mark2++) (var mark3 = 50; mark3<90; mark3++) { alert(mark1 + "<br /> "); (mark2 + "<br /> "); (mark3 + "<br />" ); console.log(mark1) console.log(mark2) console.log(mark3) } } function average () { parseInt() } </script> <body onload="marks()"> </body> </head> </html> P.S. I'm not using the prompt for the user to enter their details yet, as I wanted to test it with the marks already set. Regards Hello codingforums.com! Right, this is probably going but such a stupid newbie thread but here goes.. I've finally got myself into gear to start learning javascript. I've been watching video tutorials, learning from websites and simply learning by error. I understand the concept of for loops, but the whole nested thing doesn't seem to click for some reason. I thought i understood and managed to write a piece of code that constantly writes '*' across the screen. Could someone with some pretty damn good knowledge of javascript be able to walk me through step by step of my script to explain what actually is happening? It would help loads. here is the script, many thanks!! <script type="text/javascript"> var counter = 0; function writeStars(){ for(i=0;i<1;i++){ for(a=0;a<=counter;a++){ document.write("*"); } counter++ document.write("<br />"); } } setInterval("writeStars()", 200); </script> I have the following nested for loops: Code: for (i;i<tag('entry').length;i++) { content = content + '<tr>'; for (x;x<tag('header').length;x++) { content = content + '<td style="width:' + tdWidth + '%; border:solid 1px #000;">' + tag('item')[x].firstChild.nodeValue; + '</td>'; } x+=tag('header').length; content = content + '</tr>'; } For some reason, it seems to only loop the outer for loop once. BTW, tag() is defined, I just didn't include it. Help is appreciated. Thanks, Julian Hey everyone! I am pretty new to JS and I am having a problem figuring this loops structure out - any help would be appreciated. I am trying to add a password to an html page via an external JS file. (I know this isn't an ideal solution for securing a page - I am just trying to use this for trying to understand loops.) What I am trying to do is prompt the user to enter a password before the html page loads. If the password is correct they can enter the page. If they guess wrong the user is looped back to a prompt box to try again. If they fail 3 times they should be told via an alert box and sent off somewhere else. I have tried using a for & do while loop and was unsuccessful. I think this is the best way to go. This is what I have so far: Code: var password = prompt('All women a ',' '); var pass1 = "Psycho"; var counter = 0; if (counter < 3) { if (password = pass1) { alert('Password Correct! Click OK to enter!'); counter++ } else { alert("Password Incorrect!!!"); window.location="Lab5Part2.html"; } } else { alert("You have failed 3 times!"); window.location="http://www.google.com"; } Hey Guys, I'm currently a seasoned programmer who is in a programming class at my school. We're currently learning advanced JavaScript, and we're on the topic of nested loops. After teaching us about for and while loops, my teacher gave us a little puzzle to solve. It's kind of difficult to explain, but I'll give you guys my current code and what it outputs. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Word Reversal</title> <script type="text/javascript"> var ask = prompt("How many words do you want?",""); while (ask < "1") { alert("You have to have at least one word!"); var ask = prompt("How many words do you want?",""); } var num = parseInt(ask) + 1; var final = ""; for (var i=1; i < num; i++) { var word = prompt("What's word " + i + "?"); final = final + "Word " + i +": " + word + "<br/>"; } </script> </head> <body> <script type="text/javascript"> document.writeln(final); </script> </body> </html> The current output, when the user wants two words, and word 1 is one and word 2 is two, comes out to be: Code: Word 1: one Word 2: two Which is great, but the only problem is, this is what the output's supposed to be: Code: Word 2: two Word 1: one I'm stumped. I've had numerous programming challenges in my life which I've solved, but I'm not sure where to go next on this one. The script is supposed to use a nested loop, but what goes in what loop to reverse the order of the user's input? I asked my teacher for help, but he told me "Ask someone else." I asked another seasoned programmer in my class, who was just about as stumped as I was, so I went back to my teacher. "Well, ask another person" he replied. And can you believe this guy has a Master's Degree of Computer Science? So I'm asking you guys: the community. I hope someone will be able to help me. On top of that, I have to help and tutor two special education students in my class on this kind of stuff during class, and they can't get the project done until I get it done, as they learn from analyzing and copying my work (which my teacher told me to do). They get upset when they have nothing to code, and they end up goofing off the entire period, or using it as a study hall. I need to get them back on track, so we can move on to the next project. Please help me with this code - it would be greatly appreciated. Thank you! This is a final loops in an exercise here is my code Code: <script type="text/javascript"> var counter; for (counter=0; counter<amount.length; counter++) {} { document.writeIn(counter+"<br/>"); document.writeIn("<tr><td>"date"[counter]"</td>"); document.writeIn("<td class = 'amt'>myArray</td>"); document.writeIn("<td>"firstName[counter]"</td>"); document.writeIn("<td>"lastName[counter]"</td>"); document.writeIn("<td>"street[counter]"<br />"); document.writeIn("<td>"+street[counter]+" "+city[counter]+" "state[counter]+" "+zip[counter]+"</td></tr>); Total=total+amount[counter]; document.writeIn("<table>"); } </script> This is what i have, what do i need to do to make this more proper and written properly? thanks Hi everyone. I have a loop question. This is my assignment for my Comp Apps class. The whole thing is a store selling guitar picks. What I'm missing now is a loop. After the costumer places the order, he has the choice to go back and buy more or complete the order. In the end all the order the costumer placed adds up to the total. This is what I have so far: PHP Code: <script type="text/javascript"> var name = prompt("Welcome to Pick Center. Please enter your name", " "); alert("Hello " + name + "! Please look through our list of picks before placing your order."); var product = prompt("What would you like to buy?", ""); var quantity = prompt("How many " + product + " would you like to order?", ""); var confirming = confirm(""+ name + " you ordered " + quantity +" " + product +" picks. Is this correct?"); var price = " "; var item_discount = " "; if ( confirming == true ) { } else { alert("Refresh the page to reload and place a new order.")} if ( product == "dirtbag" ) { price = "5"; item_discount = "0.3";} else if ( product == "delrin" ) { price = "7"; item_discount = "0.2";} else if ( product == "speedpick" ) { price = "10"; item_discount = "0.5";} else if ( product == "stubby") { price = "25"; item_discount = "0.25";} else { alert("Sorry," + name + ". You entered an invalid product. Refresh the page to reload and place the order again.");} var cost_of_order = price * quantity; var discount = price * item_discount * quantity; var total = cost_of_order - discount; document.write("<br><h1> Your Order: </h1></br><br>"); document.write("Thank you for placing an order with us, <b>" + name + "</b>.<br><br>"); document.write("The cost of buying " + quantity + " " + product + " picks is <b>$" + cost_of_order + "</b>.<br><br>"); document.write("The discount for this purchase is <b>$" + discount + "</b>.<br><br>"); document.write("With discount, your total order cost is <b>$" + total + "</b>.<br><br>"); </script> I've tried reading around and I bought a couple of books but I just can't get a grasp on loops. Can someone please help me with this? Hello all. I've spent a few days now browsing this forum along with guides on the net, I'm new to JS and I'm having a bit of trouble with loops. I just don't seem to get them, I was wondering if anyone had any tips or methods (the simpler the better ) for getting these learnt and done with? Would appreciate any tips Thanks I've been asked to create a program which allows meteorologists to input a certain amount of data inputs of snowfall, and then the individual snowfall of each input itself. In my mind this should prompt me for a data input as many times as their are inputs, however, it works only for the first data input, then it returns to blank page without prompts for the second input... Any clues as to where I'm going wrong? I am working on making 2 for loops of 2 arrays to get the total of them. Then I need to get the average heights. This is for a test, yet I have not got a clue, so I need clues as I cant get it to work and I am a new coder to javascript. Code: var heights = [15,16,17,18,19]; var numbers = [2,1,6,4,2]; var average = new Array(5); average = 0 for (var heights = 0; heights <= 5; heights = heights+ 1) { total = 0 } for (var numbers = 0; numbers <= 5; numbers = numbers + 1) { total = 0 average = heights / numbers; } document.write('The average height is ' + average); Am I on the right road? I need to use this format and not functions. I have got 2 for statements but maybe I could do this with one, it is so tricky this javascript. I am doing practice problems for class (not homework), and I've gotten most of the coding down except for one stipulation. The exercise reads: "Write a program that reads input of the number of hours an employee has worked and displays the employee's total and average (per day) number of hours. The company doesn't pay overtime, so cap any day at 8 hours. Sample Run: How many days? 3 Hours? 6 Hours? 12 Hours? 5 Employee's total paid hours = 19 Employee’s average paid hours = 6.3333333" I can't figure out how to include the bolded stipulation. I've tried adding: Code: if ( sum >8 ) { sum = 8; } but I know that isn't right, and I can't think of any other solution. Can someone advise me on my work? Code: public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("How many days worked? "); int count = keyboard.nextInt(); int i = 1; int sum = 0; while (i <= count) { System.out.println("Hours? "); sum += keyboard.nextInt(); i++; } System.out.println("Employee's total paid hours= " +sum); System.out.println("Employee's average paid hours= " +(double)sum/count); } } Also! If anyone can explain to me why there has to be an initialization of " int sum = 0 ", that would be great. I just know I have to include it for this loop. |