JavaScript - (simple?) Assigning Array Values In A Compounding Loop - Keep Getting Nan Or Undefine
Okay, I am taking a js class and there is one minor bug that is driving me crazy with this assignment.
First, here is the code I wrote, then my question: Code: var games = ["Jacks","Chutes and Ladders","Extreme Uno","Bopit","Barbie Doll"]; var price = [4.00,15.99,25.00,27.99,32.00]; var inventory = [40,15,30,20,40]; //I could not figure out how to make this work without assigning values first. It was giving NaN. var subtotal = [0,0,0,0,0]; var qtySold = [0,0,0,0,0]; function chooseItem() { var answer = 0; while (answer != 6) { var orderForm = "Choose a number below:\n"; for (var i=0; i<games.length; i++) { orderForm = orderForm + (i + 1) + ".) " + games[i] + ": # in stock: " + inventory[i] + "\n"; } orderForm = orderForm + "6.) Show Sales Summary"; answer = prompt(orderForm); answer = parseFloat(answer); if(answer != 6 && answer >= 1 && answer < games.length+1) { var qty = prompt("How many " + games[answer-1] + " would you like?"); qtySold[answer-1] = parseFloat(qtySold[answer-1]) + parseFloat(qty); subtotal[answer-1] = qtySold[answer-1] * price[answer-1]; } else if (answer < 1 || answer > 6) { alert("Invalid Answer"); } else { alert("Click OK to see your summary:"); } } var summary = "Your Sales: \n"; for (var j=0; j<qtySold.length; j++) { summary = summary + qtySold[j] + " " + games[j] + " at " + currency(price[j]) + " each for a total of " + currency(subtotal[j]) + "\n"; } alert(summary); } So basically, the arrays subtotal and qtySold need to retain values in case the "customer" chooses to add more of the same item in each order. What you see above works; however, when I alert the summary, it lists all of the items, even if there were none ordered. It simply says 0, but that is not what I want. Basically, I only want the total to reflect only the items that were actually selected. I do not what to do it this way: Code: var subtotal = [0,0,0,0,0]; var qtySold = [0,0,0,0,0]; I can effectively do this by NOT assigning any values to the qtySold array in the beginning: i.e. doing it this way: Code: var subtotal = new Array(); var qtySold = new Array(); The only problem is that when I do this, I get NaN at this point: Code: qtySold[answer-1] = parseFloat(qtySold[answer-1]) + parseFloat(qty); subtotal[answer-1] = qtySold[answer-1] * price[answer-1]; obviously, this is because I am referencing qtySold[answer-1] directly in the loop - so the first time through, there is nothing assigned. I can't (just before this line) assign 0 to each array item - to get it defined because if the user goes back in and adds more, it will always reset the number back to 0, which is not what I wanted. I tried adding an if..else statement instead, but cannot figure out how to get that to work? What are my options here? Thanks! Mike Similar TutorialsSo I am working on an excercise that the User puts in a Lastname, Firstname, and a score via textboxes. When the user pushes the add student score it should show up in the text area with this format " Brown, John: 92". When looking at the logic, I understand that each text box will need to be different arrays if im right, and then I will have to concat all three arrays into the format and assign it to a variable. Then assign the variable to the value of the text area. I just cannot seem to put the function together or how you would go about it. I just need help with how to go about putting it together. The first code is my body of HTML I'm working with. Code: <body> <div id="content"> <h1>Student Scores</h1> <div id="buddy"> <b>Last Name: </b><input type="text" id="lastName" /> <b>First Name: </b><input type="text" id="firstName" /> <b>Sco </b><input type="text" id="score" /> <input type="button" id="calculate" value="Add Student Scores" /> </div> <fieldset> <legend>Student Scores</legend> <p id="tasks"><textarea id="task_list" rows="20" cols="100"></textarea></p> </fieldset> <div id="yoohoo"> <b>Average sco </b><input type="text" id="averageScore" /> <div> <div id="yes"> <p><input type="button" name="add_task" id="add_task" value="Clear Scores" /></p> <p><input type="button" name="add_task" id="add_task" value="Sort By Last Name" /></p> </div> </body> Hi Having a small problem with writing out the matches from an array using a For loop. I have two arrays, lets say arrayA and arrayB. In arrayB are numbers which are a number of miles, ie 1,2,6,4,5,6,6. And in arrayA are the days of the week. Each day of the week is associated with a mileage, ie Mon = 1, Tues = 2 etc. My script has found the largest mileage in arrayB. Next I have to find the days of the week that match this highest mileage and write these out, along the lines of "The highest mileage was 6 run on Wed, Sat, Sun." I have managed to get a For loop to work with this BUT..... I can only get it to write out the first instance of the day the match is found. ie "The highest mileage was 6 run on Wed," Pointers in the right direction to help me solve this problem would be much appreciated. [CODE] maximumDistanceIndex = 0; for (var distance = 1; distance < distanceArray.length; distance = distance + 1) { if (distanceArray[distance] > distanceArray[maximumDistanceIndex] ) { maximumDistanceIndex = distance document.write ('The maximum distance was ' + maximumDistance + ' km' + ' run on ' + dayArray[maximumDistanceIndex] ); } } [CODE] var selwindow = window.open('child1.html','_blank','resizable=yes,width='+(screen.width-500)+',height='+(screen.height-500)+''); selwindow.document.selectform.childText.value=document.getElementById('pdetails1').value; I am using this code to assign a value for textbox in the child window. It works well in Internet Explorer, but it shows an error when run in Firefox. It shows: selwindow.document.selectform is undefined. Here, "childText" is the current window textbox id, "pdetails1" is the child window text box id,"select form" is child window form id I'm developing a simple game that involves a system of interconnected nodes with unidirectional travel between nodes (similar to the circulation system!). The goal of the game is to get from a starting node to an ending node, which can be a variable number of nodes away. The program picks a random starting point, then randomly chooses one of its connecting nodes (cNodes) and pushes it onto a pathArray. A cNode is randomly chosen from this new node and it is pushed onto the pathArray. This continues for a designated number of turns, thus generating a pathArray (invisible to the player). The last element in the pathArray is the endNode and the goal of the puzzle. At each node the player is given two options of travel (though there may be more than two ways to go). One of these options MUST be the correct way if the player has not deviated from the path up until that point. If the player has deviated, this option can be any cNode. The other node is any cNode that does not lead to the endNode. The following code contains a simplified list of nodes that represents the content in my game. The function, however, is taken word for word. In this snippet, the pathArray & startNode have already been generated and I am trying to resolve how to assign "nodeChoice" as either the correct direction of travel (for a player on the correct path) or any random cNode (for a player who has deviated from the path). Keep in mind that the pathArray and cNodes lengths can be any size. Code: <script> //NODES: var nodeA = {name:"A"}; var nodeB = {name:"B"}; var nodeC = {name:"C"}; var nodeD = {name:"D"}; var nodeE = {name:"E"}; var nodeF = {name:"F"}; var nodeG = {name:"G"}; var nodeH = {name:"H"}; var nodeI = {name:"I"}; var nodeJ = {name:"J"}; var nodeK = {name:"K"}; //An array of all nodes in the system: var systemArray = [nodeA, nodeB, nodeC, nodeD, nodeE, nodeF, nodeG, nodeH, nodeI, nodeJ, nodeK]; //Connecting Nodes (cNodes): //(uni-directional, but cyclical) nodeA.cNodes = [nodeB, nodeC]; nodeB.cNodes = [nodeD, nodeE, nodeF]; nodeC.cNodes = [nodeF, nodeG]; nodeD.cNodes = [nodeI, nodeH]; nodeE.cNodes = [nodeJ]; nodeF.cNodes = [nodeK]; nodeG.cNodes = [nodeK]; nodeJ.cNodes = [nodeA]; nodeK.cNodes = [nodeA]; nodeI.cNodes = [nodeA]; nodeH.cNodes = [nodeA]; //The path chosen (generated from code not included here) var pathArray = [nodeA, nodeB, nodeE, nodeJ]; //nodeChoice will represent a cNode from any given node var nodeChoice; //chooseNode is supposed to assign nodeChoice the next element in pathArray if the player on on the right path (if at nodeB, nodeChoice = nodeE). //However, if the user has taken a different path, its cNodes will not be in pathArray in which case a random cNode is assigned to nodeChoice function chooseNode(_node) { //check each cNode to see if any are in pathArray for (var j = 0; j < _node.cNodes.length; j++) { //if a cNode is in pathArray, then we know to assign it nodeChoice... if (_node.cNodes[j] in pathArray) { nodeChoice = _node.cNodes[j]; console.log("choiceNode CORRECT: " + nodeChoice.name); //(for debugging purposes only) } //...otherwise don't do anything in this forLoop/ifStatement }; //if by this point nodeChoice is still undefined, meaning none of the current node's cNodes are in pathArray, assign it any one of its cNodes. if (nodeChoice == undefined) { nodeChoice = _node.cNodes[Math.floor(Math.random()* _node.cNodes.length)]; console.log("choiceNode INCORRECT: " + nodeChoice.name);//(for debugging purposes only) }; }; //Runtime: chooseNode(nodeB); //Result should be only nodeE.name since nodeD is not in the pathArray... console.log(nodeChoice.name); </script> ...however, nodeChoice is assigned either D, E or F randomly and we are given the troubleshooting statement "choiceNode INCORRECT: D (or) E (or) F", indicating that the if-in statement is always ignored. I know that the if-in statement doesn't work but am not sure how else to write it so that each cNode is compared the each element in pathArray, both of which can be of variable lengths... I've reading this forum for some time now and this is my first post. I hope to find an helpfull community here and to be able to help other users myself. I'm new to JS so this might be an simple question: I have an form that can be filled bij an user, some fields are calculated by Javascript. I need an code to be able to calculate 'live' the totals of the fields in the loop, that fields are the grey fields at the borro. This is (part of) my form: PHP Code: <table align="center" class="bd" border="0" cellspacing="1" cellpadding="2" width="500"> <tr> <td>Bewerking</td> <td>Prijs per uur</td> <td>Aantal uur</td> <td align="center">Totaal</td> <td>Opmerkingen</td> </tr> <?php for ($i=0; $i<=$bew_aantal_regels_corr; $i++) { ?> <tr> <td><?php if($error_bew_vergeten[$i] == "ja"){ $error_omschr = $error_omschr_bew_vergeten[$i]; include('includes/input_error.php'); } ?> <select name="bewerking[]" onChange="bew_uren(this, <?php echo $i ?>),bew_uren_tot(this, <?php echo $i ?>)"> <option></option> <?php $sql_bewerking = "SELECT omschrijving, tarief from sp_calc_werkzaamheden ORDER BY omschrijving ASC"; $res_bewerking = mysql_query($sql_bewerking,$con); while ($row_bewerking = mysql_fetch_assoc($res_bewerking)){ ?> <option <?php if($row_bewerking["omschrijving"] == $bew_omschr[$i]){ echo 'selected="selected"'; } ?> value=<?php echo $row_bewerking["tarief"] ?>><?php echo $row_bewerking["omschrijving"] ?></option> <?php } ?></select> <input type="hidden" name="bew_omschr[]" value="<?php if($bew_omschr[$i] != ''){ echo $bew_omschr[$i]; } ?>" /> </td> <td><input type="text" name="bew_tarief[]" onKeyup="bew_uren_tot(this, <?php echo $i ?>)" size="5" style="text-align:right" value="<?php if($bew_tarief[$i] != ''){ echo $bew_tarief[$i]; } ?>" /><?php if($error_bew_tarief[$i] == "ja"){ $error_omschr = $error_omschr_bew_tarief[$i]; include('includes/input_error.php'); } ?></td> <td><input type="text" name="bew_uren[]" onKeyup="bew_uren_tot(this, <?php echo $i ?>)" size="5" style="text-align:right" value="<?php if($bew_uren[$i] != ''){ echo $bew_uren[$i]; } ?>" /><?php if($error_bew_uren[$i] == "ja"){ $error_omschr = $error_omschr_bew_uren[$i]; include('includes/input_error.php'); } ?></td> <td><input type="text" name="bew_totaal[]" size="10" style="text-align:right;background-color: #f1f1f1" value="<?php if($bew_totaal[$i] != ''){ echo $bew_totaal[$i]; } ?>" readonly="readonly" /></td> <td><input type="text" name="bew_opmerkingen[]" size="75" value="<?php if($bew_opmerkingen[$i] != ''){ echo $bew_opmerkingen[$i]; } ?>" /></td> <td><input type="hidden" name="bew_id[]" value="<?php if($bew_id[$i] != ''){ echo $bew_id[$i]; } ?>" /></td> </tr> <?php } ?> <tr> <td>Regels: <input type="text" name="bew_regels" value="<?php if($bew_aantal_regels != ''){ echo $bew_aantal_regels; } ?>" size="3" /><?php if($error_bew_aantal_regels == "ja"){ $error_omschr = $error_omschr_bew_aantal_regels; include('includes/input_error.php'); } ?> <input type="hidden" name="bew_aantal_regels_oud" value="<?php if($bew_aantal_regels_oud != ''){ echo $bew_aantal_regels_oud; } ?>" size="3" /> <input type="hidden" name="bew_aantal_regels_db" value="<?php if($bew_aantal_regels_db != ''){ echo $bew_aantal_regels_db; } ?>" size="3" /></td> <td></td> <td><input type="text" name="bewerking_tot_uur" size="5" style="text-align:right;background-color: #f1f1f1"" value="<?php if($bewerking_tot != ''){ echo $bewerking_tot; } ?>" readonly="readonly" /></td> <td><input type="text"name="bewerking_tot" size="10" style="text-align:right;background-color: #f1f1f1"" value="<?php if($bewerking_tot_uur != ''){ echo $bewerking_tot_uur; } ?>" readonly="readonly" /></td> </tr> </table> I have the following code: Code: if (n==1 && g <=5) { sndPlayer1.URL ="Boy-a1.wav"; } else if (n==1 && g >5) { sndPlayer1.URL ="Girl-a1.wav"; } else if (n==2 && g <=5) { sndPlayer1.URL ="Boy-e1.wav"; } else if (n==2 && g >5) { sndPlayer1.URL ="Girl-e1.wav"; } else if (n==3 && g <=5) { sndPlayer1.URL ="Boy-i1.wav"; } else if (n==3 && g >5) { sndPlayer1.URL ="Girl-i1.wav"; } else if (n==4 && g <=5) { sndPlayer1.URL ="Boy-o1.wav"; } else if (n==4 && g >5) { sndPlayer1.URL ="Girl-o1.wav"; } else if (n==5 && g <=5) { sndPlayer1.URL ="Boy-u1.wav"; } else if (n==5 && g >5) { sndPlayer1.URL ="Girl-u1.wav"; } else if (n==6 && g <=5) { sndPlayer1.URL ="Boy-b1.wav"; } else if (n==6 && g >5) { sndPlayer1.URL ="Girl-b1.wav"; } else if (n==7 && g <=5) { sndPlayer1.URL ="Boy-b1.wav"; } else if (n==7 && g >5) { sndPlayer1.URL ="Girl-b1.wav"; } else if (n==8 && g <=5) { sndPlayer1.URL ="Boy-h1.wav"; } else if (n==8 && g >5) { sndPlayer1.URL ="Girl-h1.wav"; } else if (n==9 && g <=5) { sndPlayer1.URL ="Boy-t1.wav"; } else if (n==9 && g >5) { sndPlayer1.URL ="Girl-t1.wav"; } I was wondering what the best way to make a smaller simpler version of this code is? Would it be using a loop? If so can you help me with how to Code: <script> var rXL = ""; do { rXL = prompt("Enter more entries? Y/N"); // IF Y or N is entered, the loop should in theory exit } while (rXL != "Y" || rXL != "N"); </script> IF Y or N is entered, the above loop should in theory exit, however it results in a infinite loop :/. Does anyone know what I'm doing wrong? Thank you all . Hi guys I have what i think is a fairly simple script used for an image gallery with a next and back button. It seems to work pretty well, but i would like to make the gallery scroll round... ie when the user reaches the last picture and presses the next button again, the first image will be displayed again - and visa versa with the first image and the back button. Below is my JS, can post the small amount of HTML that calls it if necessary. Any help MUCH appreciated, been messing around with it for ages and being the newbie i am, can't seem to find any way of doing it Code: // List image names without extension var myImg= new Array(6) myImg[0]= "performance2011"; myImg[1]= "performance2005"; myImg[2]= "performance2006"; myImg[3]= "performance2007"; myImg[4]= "performance2008"; myImg[5]= "performance2009"; myImg[6]= "performance2010"; // Tell browser where to find the image myImgSrc = "../images/"; // Tell browser the type of file myImgEnd = ".jpg" var i = 0; // Create function to load image function loadImg(){ document.imgSrc.src = myImgSrc + myImg[i] + myImgEnd; } // Create link function to switch image backward function prev(){ if(i<1){ var l = i } else { var l = i-=1; } document.imgSrc.src = myImgSrc + myImg[l] + myImgEnd; } // Create link function to switch image forward function next(){ if(i>5){ var l = i } else { var l = i+=1; } document.imgSrc.src = myImgSrc + myImg[l] + myImgEnd; } // Load function after page loads window.onload=loadImg; Code: <html> <head> <title>lightning generator</title> </head> <body> <canvas id='world' width='500' height='500' style='border: 1px solid black; padding:0;'></canvas> <script type="text/javascript"> var world = { } ; world.ground = { } ; world.ground.slice = []; var ctx = document.getElementById( 'world' ).getContext( '2d' ); world.ground.make = function( GArray ){ ctx.fillStyle = '#000'; for ( var i = 0; i <= GArray.length; i ++ ){ if ( GArray[i + 1] === null ){ GArray[i + 1] = GArray[i]; } world.ground.slice[i] = GArray[i]; ctx.moveTo( i, - 500 ); ctx.lineTo( i, GArray[i] ); } }; world.ground.make( [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29] ); </script> </body> </html> it should make a simple area at the bottom of the canvas thats black., a incling with a slope of 2 and than a straight line. .....dots ar unfiled..... ..._____________ ../ ./filled area... / This is driving me crazy. I simply want to display the values of the checkboxes with a specific name. This loop executes only once, then stops, showing no error msg. I have found no similar problem elsewhere on the net and have done a ton of tests, but cannot find out why it won't continue to loop. I've included the whole html file. Please Help! Code: <HTML> <SCRIPT language="JavaScript"> function test1() { var chkLen=document.frmTable.CHK0.length; for (k=0;k<chkLen;k++) { //execution stops after one loop. no error msg. document.write(document.getElementsByName('CHK0')[k].value); } } </SCRIPT> <FORM NAME=frmTable> <TABLE BORDER=1> <TR> <TD><INPUT TYPE=CHECKBOX NAME=CHK0 VALUE='one'>1</TD> <TD><INPUT TYPE=CHECKBOX NAME=CHK0 VALUE='two'>2</TD> <TD><INPUT TYPE=CHECKBOX NAME=CHK0 VALUE='three'>3</TD> </TR> </TABLE><BR> <INPUT TYPE=BUTTON VALUE='Go' onClick=test1()> </FORM> </HTML> I am stuck on these problems and cannot figure them out! Any help would be appreciated. Thank you! Code: public int sumkj(int k, int j){ // Complete the method using a for loop that will add the numbers from k to j, // where j is greater than k int total = 0; // TODO: ADD LOOP CODE HERE return total; } // whilesum10 public int whilesum10(){ // Complete the method using a while loop that will add the numbers // from 1 to 10 int total = 0; int i = 1; // TODO: ADD LOOP CODE HERE return total; } // whilesumkj public int whilesumkj(int k, int j){ // Complete the method using a while loop that will add the numbers // from k to j, where j is greater than k int total = 0; int i = k; // TODO: ADD LOOP CODE HERE return total; } public int dosum10(){ // Complete the method using a do-while loop (i.e. condition at end of loop) // that will add the numbers from 1 to 10 int total = 0; int i = 1; // TODO: ADD LOOP CODE HERE return total; } public int dosumkj(int k, int j){ // Complete the method using a do-while loop (i.e. condition at end of loop) // that will add the numbers from k to j, where j is greater than k int total = 0; int i = k; // TODO: ADD LOOP CODE HERE return total; } public String arrayprint(){ String msg = ""; String abc[] = new String[6]; abc[0] = "a"; abc[1] = "b"; abc[2] = "c"; abc[3] = "d"; abc[4] = "e"; abc[5] = "f"; // Create a loop that will output the values stored in the array abc // using a for loop and the array length // TODO: ADD LOOP CODE HERE return msg; } public String baseballOuts(){ String msg = ""; int totalOuts = 0; // Write a set of nested for-loops that willdetermine the number of // outs in a regulation baseball game. Assume: 9 innings per game, // 2 halves per inning, 3 outs per half inning. // You solution should include a loop (outer or nested) for each // of the assumptions. // TODO: ADD LOOP CODE HERE msg = "Total number of outs in a regulation baseball game is " + totalOuts + "."; return msg; } public String factorial (int n){ String msg = ""; int factnum = 1; // Use a loop to calculate the factorial of an input integer. // Note: If the input integer is too high an error may occur even if your // logic is correct. Why? At what value of input does the error occur? // How can you adjust the method so that either the error does not occur // or the method "fails gracefully?" Write your answers in the form of // a comment here. // TODO: ADD LOOP CODE HERE msg = n + "! = " + factnum; return msg; } } I have the perfect form for a client - but its missing one thing. She sells hair clips in various colors. A user can select a hair clip color and quantity quite easily (as seen in the code below). My issue is that she wants to be able to give the user a 'special price' based on the quantity ordered by the user. Contrary to simply adding the default price of $7 over and over again based on the quantity selected. To Reiterate The way I want it to work... 1 clip is $7 2 clips are $12 3 clips are $22 5 clips are....etc. ...however, with the way that the javascript is set up now I'm only able to select one default price. This means that whatever quantity is selected -- it's simply multiplied by the number 7 to provide a total. 1 clip is $7 2 clips are $14 3 clips are $21 5 clips are....etc. If some kind soul can give their advice or point me in the right direction I would appreciate it. Code: <script type="text/javascript" src="_inc/orderform04.js"></script> <script type="text/javascript"> //<![CDATA[ window.onload = setupScripts; function setupScripts() { var anOrder1 = new OrderForm(); } //]]> </script> <form id="frmOrder"> <p> <input type="checkbox" id="chk0" /> Black Hair Clips $<span id="txtPrice0">10</span> <select id="sel0"> <option value="val0">0</option> <option value="val1">1</option> <option value="val2">2</option> <option value="val3">3</option> </select> </p> <p> <input type="checkbox" id="chk1" /> Red Hair Clips $<span id="txtPrice1">10</span> <select id="sel1"> <option value="val0">0</option> <option value="val1">1</option> <option value="val2">2</option> <option value="val3">3</option> </select> </p> <p> <input type="text" id="txtTotal" size="8" /> </p> </form> orderform04.js is located he http://www.mredkj.com/javascript/orderform04.js hello I am having a problem to add numbers store in an array. arrayValues[0][0] = 1; arrayValues[0][1] = 2; var col = 0; var sum; for ( var row = 0; row < index; i++ ) sum += arrayValues[col][row]; my result is ==> 12 it is defining my sum variable as string. even I try do do this var sum = 0; to define sum as numeric variable. my result was ==>012. Any idea, this is my first javaScritp code. Thanks. Hi Guys, How do I sum the values of an array and output the result using document.write? Say my array is var number=new Array(1.234,56.43,1.02); THANKS Thought this wud work? Code: <script type="text/javascript"> var x = [1, 2, 3, 4, 5, 6, 7, 8, 9]; document.write(sum(x)); </script> HI, I am new to JavaScript and need help with a code //names of couples stored in array var contestantNamesArray = ['Tom and Nazia', 'Pat and Dan', 'Sandra and Kofi', 'Ian and Adele', 'Paul and Costas']; //points awarded by judges and audience stored in arrays var judgesPointsArray = [2,1,5,4,3]; var audiencePointsArray = [4,5,2,3,1]; //Part (i)(a) //new array to store the combined points for each couple var combinedPointsArray = new Array (4); //Part (i)(b) //loop to add the judges and the audience points for each couple and to store them in the combined points array for (var score = 0; score < combinedPointsArray.length; score = score + 1) { combinedPointsArray[score] = judgesPointsArray[score] + audiencePointsArray[score]; } //Part(i)(c) //loop to find and write out the maximum number of points scored maxPointsScoredIndex = 0; for (var score = 1; score < combinedPointsArray.length; score = score + 1) { if (combinedPointsArray[score] > combinedPointsArray[maxPointsScoredIndex]) { maxPointsScoredIndex = score; } } document.write ('The maximum number of points was ' + combinedPointsArray[maxPointsScoredIndex] + '<BR>'); //Part (iii) //Add code that will // -- write out a heading for the list of couples scoring the maximum // -- write out the names of all the couples with the maximum number of combined points // keeping score of how many they are // -- at the end, write out whether a dance-off is required or not, depending on how many couples scored the maximum It's the third part that I'm struggling with. Could someone help me? Thank you! apparently this is supposed to be a loop... I got it off another topic here and it made NOOOO sense Code: //dandavis's ES5 Array methods: (function ArrayMethods(){var o=Array.prototype,it,i, e=eval('( {map:Z0,r=[];for(;i<m;i++){if(i in t){r[i]=a.call(b,t[i],i,t);}}return r;},filter:Z0,r=[],g=0;for(;i<m;i++){if(i in t&&a.call(b,t[i],i,t)){r[g++]=t[i];}}return r;},every:Z0;return m&&t.filter(a,b).length==m;},some:Z1;for(;m--;){if(m in t&&a.call(t,t[m],m,t)&&!--i){return true;}}return false;},lastIndexOf:Zb||-1;for(;m>i;m--){if(m in t&&t[m]===a){return l;}}return-1;},indexOf:Zb||0;for(;i<m;i++){if(i in t&&t[i]===a){return i;}}return-1;},reduce:Z0,r=b||t[i++];for(;i<m;i++){r=a.call(null,r,t[i],i,t);}return r;},reduceRight:Zm-1,r=b||t[i--];for(;i>-1;i--){r=a.call(null,r,t[i],i,t);}return r;},forEach:function(a,b){this.concat().map(a,b);return this;}})'.replace(/Z/g,"function(a,b){var t=this.concat(),m=t.length,i="));for(it in e){i=o[it];o[it]=i||e[it];} }());//end ArrayMethods() someone want to explain it to me? here is some more Code: (function(){var o=Array.prototype,it,i,e={ map:function(a,b){var t=this.concat(),m=t.length,i=0,r=[];for(;i<m;i++){if(i in t)r[i]=a.call(b,t[i],i,t)}return r}, filter:function(a,b){var t=this.concat(),m=t.length,i=0,r=[],g=0;for(;i<m;i++){if(i in t&&a.call(b,t[i],i,t)){r[g++]=t[i]}};return r}, every:function(a,b){var t=this.concat(),m=t.length,i=0;return m&&t.filter(a,b).length==m}, some:function(a,b){var t=this.concat(),m=t.length,i=1;for(;m--;){if(m in t&&a.call(t,t[m],m,t)&&!--i){return!0}}return!1}, lastIndexOf:function(a,b){var t=this.concat(),m=t.length,i=b||-1;for(;m>i;m--){if(m in t&&t[m]===a){return l}}return-1}, indexOf:function(a,b){var t=this.concat(),m=t.length,i=b||0;for(;i<m;i++){if(i in t&&t[i]===a){return i}}return-1}, reduce:function(a,b){var t=this.concat(),m=t.length,i=0,r=b||t[i++];for(;i<m;i++){r=a.call(null,r,t[i],i,t)}return r}, reduceRight:function(a,b){var t=this.concat(),m=t.length,i=m-1,r=b||t[i--];for(;i>-1;i--){r=a.call(null,r,t[i],i,t)}return r}, forEach:function(a,b){this.concat().map(a,b)} };for(it in e){i=o[it];o[it]=i||e[it]}}()); //end Array.16 injection it has something to do with eval... whats eval? sigh I hate arrays this is so confusing to try and read >< Hello, I have a homework assignment to complete and I don't understand 2 particular parts. I need to design a game that does the following: Based on assignment 3, write a program that allows you and the computer to take turns and guess each other's secret number (between 1 and 100); Requirements: * You and your opponent (computer) take turns to guess. * You and your opponent gives simple hints like in assignment 3 for each round. * Show how many rounds have passed. * Keep guessing record and display it to assist the game play. The guessing of the numbers needs to be simultaneous, and the professor wants us to use a while loop and an array. It is based on a previous assignment, in which we designed a program that would ask the user to guess a number between 1-100 that the computer generated. The user is prompted by alerts that say "too high" or "too low" and then is told when they guess correctly. This I understand, but I am confused about how to modify it to fit the new assignment. Here is the code I have: Code: <html> <head> <title> Homework #3 </title> <script type="text/javascript"> var randomNumber = Math.floor (Math.random()*100)+1; { var compNumber; var compNumber = Math.floor (Math.random()*100)+1; } { var copyArray, index; copyArray = [] index = 0; while (index < strArray.length) { copyArray[index] = parseFloat(strArray[index]); index = index + 1; } return copyArray; } function compGuess () { document.getElementById("compGuessBox").value=compNumber; } function Check() // Assumes: guessBox containes a guess // Results: displays text saying if guess is too high, too low, or correct { var userNumber; userNumber = document.getElementById("guessBox").value; userNumber = parseFloat(userNumber); if (userNumber < randomNumber) { alert("Too Low!"); } if (userNumber > randomNumber) { alert("Too High!"); } if (userNumber == randomNumber) { alert ("Correct!"); } } </script> </head> <body style="background-color:Lavender"> <h1> <div style="text-align:center"> Guess the Number the Computer has Chosen! </h1> <p> <div style="text-align:center"> <input type= "text" id="compGuessBox" size="10" value="" /> <input type="button" value="Click for Guess" onclick="compGuess();" /> </p> <p> <div style="text-align:center"> <input type="button" value="Too Low!" onClick="FUNCTION TO MAKE IT GUESS AGAIN HIGHER" <input type="button" value="Too High!" onClick="FUNCTION TO MAKE IT GUESS AGAIN LOWER" <input type="button" value="Correct!" </p> <p> <div style="text-align:center"> The Computer is Thinking of a Number Between 1-100. Enter your Guess: <input type="text" id="guessBox" size="10" value="" /> </p> <p> <input type="button" value="Check your Answer" onclick="Check();" /> </p> </body> </html> Obviously it doesn't work. My questions a 1.) How can I use an array to display the guesses? 2.) How can I use a while loop to allow the computer and user to take turns guessing each other's numbers? I'm sorry if these are too broad--I genuinely do not know how to proceed from here. I'm going to (hopefully) see the professor to ask these questions as well, but I thought I'd ask here just in case our schedules can't match up. Thank you in advance! I have a checkbox with an id="chk" and a html table (myTable) loaded from a query where one of the columns is the record status (td id="RecStatus"). When I click the checkbox "on", I'm calling a function that I want to go through all records in the table and hide the ones with a RecStatus of "closed". Here's what I have thus far; I know I'm very close but I'm having issues building my array. Code: function killSomeRows(){ var cell=document.getElementById("RecStatus"); var tbl=document.getElementById("myTable"); var numRows=tbl.rows.length; var row=document.getElementById("displayRow"); var i=0 //myArray is set to the # of Rows in my table var myArray = new Array(numRows); //I start my for loop and this is where I am lost for (i=0; i<=numRows; i++){ //In here I want to go through each row in my table and if the "RecStatus" cell = 'Closed' and my checkbox.checked==true, I want to change the style.display = 'none'. //else I want those rows with a RecStatus of 'Closed' to be visible //using style.display = '' if (RecStatus == 'Closed' && chk.checked==true) document.getElementById(row where status is closed).style.display = 'none'; else document.getElementById(row where status is closed).style.display = ''; } } I can get it to hide the 1st record in the table if that record is closed when I click/unclick the checkbox but it appears I do not have the array set up and then the for loop is not going through each record in the array. I'm at a loss....I'm very new to javascript and have been looking at this all day. Any help is appreciated...thanks Cypress hi, I have this keypressed function: Code: function keyPressed(event, input) { if (event.keyCode == 8) { return true; } var char = event.which ? event.which : event.keyCode; char = String.fromCharCode(char); var exers = "1234 1234 1234"; return (exers.charAt(input.value.length) == char); } This function allow me to press in order the numbers in array (index0). It is works very well. But i want to add an array with more exercises like: Code: var exerc = new Array(); exerc[0]= "1234 1234 1234"; exerc[1] = "5678 5678 5678"; exerc[2] = "9012 9012 9012"; Also, i have a dropdown menu that parser options from a xml file: Code: <form> <select style="width:100px" id='courses'> </select> </form> and my xml file looks like: Code: <courses> <course title="exercise 1"> <lesson>1234 1234 1234</lesson> </course> <course title="exercise 2"> <lesson>5678 5678 5678</lesson> </course> <course title="exercise 3"> <lesson>9012 9012 9012</lesson> </course> . . . </courses> *I write the same index because i have two input field. I see the first choose (depend on dropdown) in first input, and i rewrite the same exercise in the second input. So, it's something like an exercise for me and i stack here. - I repeat. It is work with only one index very well. The problem is that, when i add more that one index in the array. Any suggestion about my problem?Javascript it is not my strong point I try this but it is doesn't work.Baybe it is totally wrong! Code: function keyPressed(event, input) { if (event.keyCode == 8) { return true; } var char = event.which ? event.which : event.keyCode; char = String.fromCharCode(char); var exerc = new Array(); exerc[0]= "1234 1234 1234"; exerc[1] = "5678 5678 5678"; exerc[2] = "9012 9012 9012"; for (i=0;i<exerc.length;i++) { document.getElementById("courses").selectedIndex; } return (exers.charAt(input.value.length) == char); } I'm having problems with selecting values from array. I have a dropdown box where you choose what fruit you want to buy. When selected the array should assign 2 values to that fruit. I don't know how to do that. Here's what I have.. I added comments. Javascript part: Code: <script type="text/javascript"> function Fruits() { var selectfruit = newArray( //assigning values to fruit selected from dropdown box newArray("Banana", 1, 1), newArray("Apple", 1.2, 0.5), newArray("Mango", 1.1, 0.9), newArray("Orange", 0.1, 9.99)); var howmanyfruits = Number(document.getElementById("howmanyfruits").value); // how many fruits are you buying var totalfruitsowned = Number(document.getElementById("totalfruitowned").value); // How many fruits do you already have /* cash and coupons needed to buy fruits. cash is cpst for 1 fruit. coupons is cost for 1 fruit cash_all is cost for all fruits you're buying coupons_all is cost for all fruits you're buying each fruits requires cash AND coupons to be bought. Cash and coupons are tied to the first values in Array. Eg. If you choose Apple that value would be 1.2 The 'fruitsmaxtobuy' variable is not tied to the first value, but the second one in array. If you choose Apple that value would be 0.5. */ var cash = Math.round(((totalfruitsowned * 0.51 * selectfruit) + 700)*10)/10; var coupons = Math.round(((totalfruitsowned * 0.51 * selectfruit) + 850)*10)/10; var cash_all = Math.round((howmanyfruits * cash)*10)/10; var coupons_all = Math.round((howmanyfruits * coupons)*10)/10; var fruitsmaxtobuy = Math.round((totalfruitsowned * 0.12 * selectfruit)*10)/10; /* Display Error if nothing is entered or if you forget to enter total fruits */ if (((howmanyfruits=="" || howmanyfruits==null) && (totalfruitsowned=="" || totalfruitsowned==null)) || ((howmanyfruits==Number(document.getElementById("howmanyfruits").value)) && (totalfruitsowned=="" || totalfruitsowned==null))) {document.getElementById("cash").innerHTML = "Error"; document.getElementById("coupons").innerHTML = "Error"; document.getElementById("cash_all").innerHTML = "Error"; document.getElementById("coupons_all").innerHTML = "Error"; document.getElementById("fruitsmaxtobuy").innerHTML ="Error"} else { document.getElementById("cash").innerHTML = cash; document.getElementById("coupons").innerHTML = coupons; document.getElementById("cash_all").innerHTML = cash_all; document.getElementById("coupons_all").innerHTML = coupons_all; document.getElementById("fruitsmaxtobuy").innerHTML =fruitsmaxtobuy} } </script> HTML part: Code: <form action="" id="fruitcost"> <table align="center" width="37.5%" cellpadding="0" cellspacing="0"> <tbody> <tr> <th colspan="2" align="center">Fruit cost calcultor</th> </tr> <tr> <td>Select Fruit:</td> <td align="center"><select id="selectfruit"> <option>Banana</option> <option selected>Apple</option> <option>Mango</option> <option>Orange</option> </select> </td> </tr> <tr> <td>Total Fruits Owned:</td> <td align="center"><input id="totalfruitsowned" type="text" /></td> </tr> <tr> <td>How many fruits are you buying:</td> <td align="center"><input id="howmanyfruits" type="text" /></td> </tr> <tr> <td>Money Needed to buy 1 fruit:</td><td><font id="cash"></font></td> </tr> <tr> <td>Coupons Needed to buy 1 fruit:</td><td><font id="coupons"></font></td> </tr> <tr> <td>Money Needed:</td><td><font id="cash_all"></font></td> </tr> <tr> <td>Coupons Needed:</td><td><font id="coupons_all"></font></td> </tr> <tr> <td>Nr. of fruits you can buy:</td><td><font id="fruitsmaxtobuy"></font></td> </tr> <tr> <td align="center" colspan="2"><input type="button" value="Submit" onclick="Fruits()" /></td> </tr> </tbody> </table> </form> |