JavaScript - Trouble With For Loop/array
All I am trying to pull the data from an array and place it in a table. If I assign index 0 it works as desired. I then placed it inside a foor loop and changed the index to a variable and I get "undefined". Here is the code snipet:
document.write("<table width='500'>"); document.write("<tr><td width='75%'>Product:</td><td width='25%' align='center'>Cost</td></tr>"); for (i=0; i<(itemPrice.length); i++); { document.write("<tr><td>" + itemName[i] + "</td><td align='right'>" + itemPrice[i] + "</td></tr>"); totalcost = totalcost + itemPrice[i]; } document.write("<tr><td>The total is:</td><td align='right'>" +"$ "+totalcost+ "</td></tr>"); document.write("</table>"); compared to some of the samples I have seen I apologize if this is too elementary. rneaul Similar TutorialsI'm just a beginner with JS and having trouble with the code for my array and FOR loop. I'd like the names of these animals to be listed on separate lines. Am I way off here? I wasn't sure if the for statement had to be within a function. I've spent hours trying to figure this out and appreciate any help. <script type="text/javascript"> var animal = new Array(4); animal[0] = "dog"; animal[1] = "cat"; animal[2] = "bird"; animal[3] = "rabbit"; var counter = 0; function writeAnimal () { for (var counter = 0; counter== 4; counter++) { document.write(animal[0]); document.write("<br />"); } } </script> Hi This part of the script should ask the user which type of shape they'd like to calculate the area of, then convert whatever they enter to uppercase so that the test condition can be eventually falsified when the user enters 'c, C, s, S, r or R'. I've consulted the w3 school, and as far as I can tell I'm formatting it correctly. I think the problem may be in the syntax of the test condition. Code: while (shapeType != 'C' || shapeType != 'S' || shapeType != 'R') { shapeType = prompt("Which type of Shape would you like to find the area of?" + '\n' + "For a circle, enter C" + '\n' + "For a square, enter S" + '\n' + " For a rectangle, enter R"); shapeType = shapeType.toUpperCase(); } However, firebug reports that 'shapeType is null'. How can this be? I've declared shapeType in the head as a global variable. Any ideas? Jenny This is the loop I'm trying to use to check for bullets hitting rocks. the function worked if I used actual numbers instead of the j variable, but I wanted to loop through all the rocks. Can anyone see why the inner function loses the j index and says asteroids[j] is undefined? the hit test is removing the bullets! it's working! the asteroids[j] was used in the hit test! I'm getting testy. LOL Code: for(z in player.bullets){ for(j in asteroids){ if( pnpoly( asteroids[j].points_x, asteroids[j].points_y, player.bullets[z].x - asteroids[j].x, player.bullets[z].y-asteroids[j].y)==true) { player.bullets.shift(); asteroids[j].hits++; for(i in asteroids[j].points_x){ asteroids[j].points_x[i]*=.5; asteroids[j].points_y[i]*=.5; } }; } Here's the whole script. This is the asteroids script somebody needed help with a few days ago. I just couldn't resist making this. I love asteroids so much it's hard to describe. That game was simply the most awesome thing ever at the time. (I'm a product of the eighties) Code: <html> <head> <title></title> <script type="text/javascript" src="excanvas.js"></script> </head> <body> <script> function pnpoly(xp, yp, x, y){var c=0;for(i in xp){ j=i++;if((((yp[i]<=y)&&(y<yp[j]))||((yp[j]<=y)&&(y<yp[i])))&&(x<(xp[j]-xp[i])*(y-yp[i])/(yp[j]-yp[i])+xp[i])){c =!c}} return c} var canvas = null; var c2d = null; //... window.onload = init; function init() { thrustFlame=false asteroids = [{ x: 470, y: 290, angle: 1.71, inertia: .5, inertiaAngle: 1.2, points_x: [-30, -27, 5, 15, 30, 15,-5], points_y: [ -5, 15, 30, 27, -5, -25, -30], hits:0 }, { x: 270, y: 290, angle: 1.71, inertia: .75, inertiaAngle: 1.9, points_x: [-30, -10, 0, 20, 40, 20, -10], points_y: [0, -20, -50, -30, 0, 20, 20], hits:0 }] player = { x: 50, y: 50, angle: 1.71, inertia: 0, inertiaAngle: 0, bullets:[] } canvas = document.getElementById('canvas'); ctx = canvas.getContext('2d'); setInterval(step, 60); } function step() { for (i in asteroids) { asteroids[i].angle += i % 2 == 0 ? .05 : -.05 asteroids[i].x < 0 ? asteroids[i].x = canvas.width : asteroids[i].x %= canvas.width asteroids[i].y < 0 ? asteroids[i].y = canvas.height : asteroids[i].y %= canvas.height asteroids[i].x += Math.sin(asteroids[i].inertiaAngle) * asteroids[i].inertia; asteroids[i].y += -Math.cos(asteroids[i].inertiaAngle) * asteroids[i].inertia } ctx.fillStyle = "rgb(0,0,0)" ctx.fillRect(0, 0, canvas.width, canvas.height); for (u = 0; u < asteroids.length; u++) { ctx.save(); ctx.beginPath() Asteroid_draw(asteroids[u]); ctx.closePath(); ctx.strokeStyle = "#eeeeff"; ctx.stroke(); ctx.restore(); } ctx.save(); ctx.beginPath() Player_draw(player); ctx.closePath() ctx.strokeStyle = "#eeeeff"; ctx.stroke(); ctx.restore() if(thrustFlame){ ctx.save(); ctx.beginPath() Player_drawFlame(player); ctx.closePath() ctx.strokeStyle = "#ff0000"; ctx.stroke(); ctx.restore() thrustFlame=false } player.x < 0 ? player.x = canvas.width : player.x %= canvas.width player.y < 0 ? player.y = canvas.height : player.y %= canvas.height if (player.inertia > .025) player.inertia -= .025 player.x += Math.sin(player.inertiaAngle) * player.inertia; player.y += -Math.cos(player.inertiaAngle) * player.inertia for(i in player.bullets){ player.bullets[i].timer++; if(player.bullets[i].timer > player.bullets[i].range)player.bullets.shift() player.bullets[i].x < 0 ? player.bullets[i].x = canvas.width : player.bullets[i].x %= canvas.width player.bullets[i].y < 0 ? player.bullets[i].y = canvas.height : player.bullets[i].y %= canvas.height player.bullets[i].x += Math.sin(player.bullets[i].inertiaAngle) * player.bullets[i].inertia; player.bullets[i].y += -Math.cos(player.bullets[i].inertiaAngle) * player.bullets[i].inertia ctx.save(); ctx.beginPath() ctx.fillStyle="rgba(255,255,0,1)" ctx.arc(player.bullets[i].x,player.bullets[i].y,1.5,0,3.14,true) ctx.fill() ctx.closePath() ctx.restore(); } for(z in player.bullets){ for(j in asteroids){ if( pnpoly( asteroids[j].points_x, asteroids[j].points_y, player.bullets[z].x - asteroids[j].x, player.bullets[z].y-asteroids[j].y)==true) { player.bullets.shift(); asteroids[j].hits++; for(i in asteroids[j].points_x){ asteroids[j].points_x[i]*=.5; asteroids[j].points_y[i]*=.5; } }; } } } function Asteroid_draw(obj) { ctx.translate(obj.x, obj.y) ctx.rotate(obj.angle); ctx.moveTo(obj.points_x[0], obj.points_y[0]); for (i = 0; i < obj.points_x.length - 1; i++) { ctx.lineTo(obj.points_x[i], obj.points_y[i]); } ctx.lineTo(obj.points_x[0], obj.points_y[0]) } function Player_draw(obj) { ctx.translate(obj.x, obj.y); ctx.rotate(obj.angle); //Points {0,-12}{7,5}{-7,5} ctx.moveTo(0, -12); ctx.lineTo(7, 4); ctx.lineTo(-7, 4); ctx.moveTo(-7, 4) ctx.lineTo(0, -12); } function Player_drawFlame(obj) { ctx.translate(obj.x, obj.y); ctx.rotate(obj.angle); ctx.moveTo(-2, 2); ctx.lineTo(0, 12); ctx.lineTo(2, 2); } document.onkeydown = function (event) { keyDown(event) }; function keyDown(event) {event=!event?window.event:event if (event.keyCode == 32) { player.bullets.push({x:player.x,y:player.y,inertia:player.inertia+10,inertiaAngle:player.angle,timer:0,range:40}) } if (event.keyCode == 37) { player.angle -= .1 } /*left*/ else if (event.keyCode == 39) { player.angle += .1 } /*right*/ else if (event.keyCode == 38) { thrustFlame=true var x1= Math.cos(player.inertiaAngle)* player.inertia; var y1= Math.sin(player.inertiaAngle)* player.inertia; var x2= Math.cos(player.angle)* .2; var y2= Math.sin(player.angle)* .2; var xR= x1 + x2; var yR= y1 + y2; var lengthR= Math.sqrt(xR*xR+yR*yR); if (lengthR==0){angleR=0} var angleR= Math.acos(xR/lengthR); if (yR<0)angleR= 0-angleR; player.inertia=lengthR // player.inertiaAngle = (player.inertiaAngle*19 + player.angle) / 20 player.inertiaAngle =angleR } /* up*/ else if (event.keyCode == 40) { player = { x: 50, y: 50, angle: 1.71, inertia: 0, inertiaAngle: 0 } } /*down*/ } </script> <canvas id="canvas" width="600" height="600"></canvas> </body> </html> I'm using a loop to get the attributes of a series of <a> tags in an xml. Here's the code: Code: function getAttributes(){ for(var i=0;i <= totalSteps;i++){ whichLink = xmlDoc.getElementsByTagName("xml")[0].getElementsByTagName("a")[i].attributes.getNamedItem("href").value.split("?"); alert(whichLink); if(whichLink[1]=="correctLink"){ alert("correctLink detected"); myMessage += whichLink[0]; } } displayMessage(); } When I run the function, I get a "Object required" error for the getElementsByTagName("a")[i] line, and displayMessage() won't fire. The weird thing is, the alert(whichLink); and alert("correctLink detected"); commands both work correctly, and when I replace the i variable with a digit, like 1 , everything works smoothly (save for the fact that it only returns one of the urls I'm looking for). So something odd is going on with my loop variable, but I'm at a loss as to what. Anyone have any ideas? Appreciated as always, ~gyz Hi! I'm new to this forum and almost completely new to programming of any kind, so this may be a very easy, obvious fix; I'm just not sure. Below is a very simple script I wrote partially based on random example scripts. I think an error is generated when the while loop is first executed, because any code I place after the loop is not executed. My guess is that when null is returned, it crashes and stops executing the code. Is that the problem? If so, do you have any ideas for how I could fix it? Thanks in advance for your help! HTML: Code: <a href="javascript:expand(document.getElementById('exp1'))">SeeText</a> <div id="exp1" style="display:none"> <p>SomeText</p> </div> <a href="javascript:expand(document.getElementById('exp2'))">SeeText</a> <div id="exp2" style="display:none"> <p>SomeText</p> </div> Javascript: Code: function expand(param) { i=0; id="exp1"; if (param.style.display=="none") { while (getElementByID(id)) //This seems to be the trouble area. { document.getElementById(id).style.display="none"; i++; id="exp"+String(i) } } param.style.display=(param.style.display=="none")?"":"none"; } I have the following code: ... var numberoffiles = array(); for (i = 1; $i <= totalNumberOfFiles; i++) { numberoffiles[i] = i; } ... I get an error saying that numberoffiles is undeclared or something What am I doing wrong? Do I need to declare it a global variable or something?? ALSO, why can't I do this: numberoffiles[] = i; I've seen code snippets that assign to the end of an array like this (Or maybe my problem is the scope of the variable??) Thanks OM I am trying to create a simple auto-calculate function for a webpage. What should be happening: The 'onchange' command should pass the 'price' of the item to the function, the function should then cycle through all the dropdowns (or checkboxes or fields) and calculate the total. What is happening: It is only picking up the last checkbox. It seems that the 'for' loop only remembers the last item in the array. What am I doing wrong? How can I get the code to remember all the items? thanks, Code: <script language="JavaScript" type="text/javascript"> function calculateTotal(price) { var total = 0; var cList = ['sel1','sel2','sel3']; for (i=0;i<2;i++); var select = GetE(cList[i]); total+= price * (select.options[select.selectedIndex].value); GetE("totalShow").innerHTML = total.toFixed(2); } function GetE(id) {return document.getElementById(id); } </script> <html> <head></head><body> <form id="form1" name="form1" method="post" action=""> <select name="sel1" id="sel1" onchange="calculateTotal(100)"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select><br><br> <select name="sel2" id="sel2" onchange="calculateTotal(200)"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select><br><br> <select name="sel3" id="sel3" onchange="calculateTotal(300)"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select><br><br> </form> <br>total <span id="totalShow">0.00</span> </body></html> Hi i start of with a some csv data and convert this into an array. The resulting array looks like the following [["Apple", "64"], ["Banana", "20"], ["pear", "12"], ["Orange", "16"]] But i need this to be formatted as below without the quotes around the second value. [["Apple", 64], ["Banana", 20], ["pear", 12], ["Orange", 16]] Im not sure how to achieve this. I guess i need to loop through the array and strip out the quotes but im failing to get this working. Help! I have an array, I can not figure out how to take myTemplateholder = myTemplateholder.replace(" "+children[child],children[child]+"<div id='questionRadio'><input type='radio' name='answer' value='Y' /> Y <input type='radio' name='answer' value='N' /> N <input type='radio' name='answer' value='NA' /> N/A<br /></div>");} to display to separate lines. Right now, if there is more than one value, it gets added together. Here's the rest of the code: Code: function showText(){ // var myTemplateholder = document.getElementById('myTemplateholder').innerHTML; // document.getElementById('showMe').innerHTML = myTemplateholder; var children = new Array('Chills','Fatigue','Fever','Health History','Screening','Eye-ROS','Skin','Assessment','General Appearance','Vitals','Hearing','200','300','400','500'); var myTemplateholder = $('#myTemplateholder').text(); myTemplateholder = myTemplateholder.replace("Sections ",""); myTemplateholder = myTemplateholder.replace("History","<div id='templateHeader'>History</div>"); myTemplateholder = myTemplateholder.replace("ROS","<div id='templateHeader'>ROS</div><br>"); myTemplateholder = myTemplateholder.replace("Exam","<div id='templateHeader'>Exam</div>"); myTemplateholder = myTemplateholder.replace("ICD9","<div id='templateHeader'>ICD9</div>"); for(child in children) { myTemplateholder = myTemplateholder.replace(" "+children[child],children[child]+"<div id='questionRadio'><input type='radio' name='answer' value='Y' /> Y <input type='radio' name='answer' value='N' /> N <input type='radio' name='answer' value='NA' /> N/A<br /></div>"); } $('#showMe').html(myTemplateholder); } I'm totally stuck! Thanks for bearing with a newbie - any help would be greatly appreciated. I am trying to sort an array of strings based on the location of a string called "this.oText.value" inside an array of strings called "aList." If "this.oText.value" comes earlier in an entry in aList (call it "a") than another entry "b", I want "a" to appear before "b". Clearly, there is something very wrong with my code. It really isn't doing anything as of right now. Code: aList.sort(sortArray); function sortArray(a,b) { if(a.toLowerCase().indexOf(this.oText.value.toLowerCase()) < b.toLowerCase().indexOf(this.oText.value.toLowerCase())) return 1; else if(a.toLowerCase().indexOf(this.oText.value.toLowerCase()) > b.toLowerCase().indexOf(this.oText.value.toLowerCase())) return -1; else return 0; } Array.prototype.each = function (fn) { this.map(fn) } This is my each function that works great in every other browser but IE. UGH! What am I doing wrong? the error points to the this in the function. Is it that IE doesn't like map? Has anyone seen this before? I thought my code was correct. Works perfect in FF, chrome and opera. the canvas text doesn't work in opera, but it does render the features so the each function is working. I'll post the code if needed, but it's huge. here's the script running. http://www.pdxbusiness.com/canvas/golf/ Short version: I'm having trouble with "moving subarrays" in a multidimensional associative array. Long version: (Yes, I know that there's technically no such thing as a js associative array and that I'm actually using a generic object.) This is one of those annoying questions for which significant code can't be shown. I'm fetching a JSON object from PHP and parsing it as multi-dimensional associative array that comes out with this "structure": Code: obj[regions][variables][years] = value; My presentation logic works fine for that. Year data is presented for each variable, and variables are grouped by region. For reference, if needed, the display is tabular and similar to this: Code: Regions | Variables | 2003 | 2004 | 2005 ========================================= | measure1 | abcd | efgh | ijkl ================================= county1 | measure2 | mnop | qrst | uvwx ================================= | measure3 | yzab | cdef | ghij ========================================= | measure1 | abcd | efgh | ijkl ================================= county2 | measure2 | mnop | qrst | uvwx ================================= | measure3 | yzab | cdef | ghij ========================================= | measure1 | abcd | efgh | ijkl ================================= county3 | measure2 | mnop | qrst | uvwx ================================= | measure3 | yzab | cdef | ghij ========================================= | measure1 | abcd | efgh | ijkl ================================= county4 | measure2 | mnop | qrst | uvwx ================================= | measure3 | yzab | cdef | ghij ========================================= My problem comes from trying to allow the option to reorganize the grouping - that is, turning it into regions grouped by variable. The display logic can handle it, but I can't get the array handling code right. The desired secondary structure is Code: obj[variable][region][year] = value; Some things I've tried: Code: /* obj is in the format of obj[region][variable][year] = value */ data_arr = new Array(); for (var region in obj) { for (var variable in obj[region]) { for (var year in obj[region][variable]) { /* fail one */ data_arr[variable][region][year] = obj[region][variable][year]; /* data_arr[variable] is undefined */ /* fail two */ y = obj[region][variable][year]; y_arr = new Array(); y_arr[year] = y; r_arr = new Array(); r_arr[region] = y_arr; data_arr[variable] = r_arr; /* only the values from the last iteration are displayed */ /* fail three */ y = obj[region][variable][year]; y_arr = new Array(); y_arr[year].push(y); r_arr = new Array(); r_arr[region].push(y_arr); data_arr[variable].push(r_arr); /* y_arr[year] is undefined */ } } } And then other permutations of those three. I could run through it easy if not needing the textual index, but that's actually part of my display data, so it has to stay. Can anyone help me with what I'm overlooking? 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! 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! 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 I am having a hard time figuring this out, I have two simple arrays and I want to populate one by asking a visitor to enter information, it goes something like this... Code: var country = new Array(5); c_list[0] = "USA"; c_list[1] = "UK"; c_list[2] = "France"; c_list[3] = "Germany"; c_list[4] = "Spain"; var president = new Array(); // Last name only president[0] = window.prompt("President of USA?", ""); // Obama president[1] = window.prompt("Prime Minister of UK?", ""); // Brown president[2] = window.prompt("President of France?", ""); // Sarkozy president[3] = window.prompt("Prime Minister of Germany?", ""); // Merkel president[4] = window.prompt("President of Spain?", ""); // Zapatero Now the question is, how do I use a simple for loop to use the names entered and populate the second array? Any help would be very kindly appreciated. Thank you my assignment ----------------------------------- write a while loop that prompts user to enter name add their names to an array if they enter "exit" end the prompting sort array and list in sorted order ----------------------------------- this is what i got so far. sooo confused because i cant get the user input into an array. error console says i need ";" before the "var names[loopCounter] = prompt("enter","");" confused about this also var names = new Array(); var loopCounter; loopCounter = 0; while (names != "exit") { var names[loopCounter] = prompt("enter name",""); loopCounter++ } var i; names.sort(); for (i=0;i<names.length;i++) { document.write(names[i] + "<br>"); } I'm new to Javascript and having some difficulty understanding why I cannot get this code to continuously loop the captions in the array on the screen. The first caption in the array with appear, hold as per the setTimeout cycle and then disappear, but the next caption never comes up. 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>Untitled Document</title> <script type="text/javascript"> <!-- var caption=new Array() caption[0]="Caption1" caption[1]="Caption2" caption[2]="Caption3" var x=0 //--> </script> </head> <html> <body> <script type="text/javascript"> <!-- function cycle(){ document.write(caption[x]) if(x<3) x++ else x=0 setTimeout("cycle()",1000) } cycle() //--> </script> </body> </html> I'm sure this is probably a simple fix, or at least I hope it is. So any assistance is appreciated. Thank you Hi, I know this is painfully obvious, but I can't get my head around it. Basically, these loops: Code: for (var p=0; p < routeInfo.length; p++) { times = routeInfo[p].getElementsByTagName("time"); dirs = routeInfo[p].getElementsByTagName("dirs"); dist = routeInfo[p].getElementsByTagName("dist"); for (q=0;q<dirs.length;q++) { count++; time = GXml.value(routeInfo[p].getElementsByTagName("time")[q]); dir = GXml.value(routeInfo[p].getElementsByTagName("dirs")[q]); dist = GXml.value(routeInfo[p].getElementsByTagName("dist")[q]); if (time.length>1) { way+='<div class="dir">'+count+'. '+dir+'</div>'+'<div class="results"><div class="time">'+time+'</div><div class="dist">'+dist+'</div><br><br>'; } else way+='<div class="dir">'+count+'. '+dir+'</div><br>'; } } outputs lines of text, with two <br> between them. What I want is for if it's the last loop for that only to be one <br> so I'm thinking something like this: Code: if (last loop) {end =<br>} else end=<br><br> ... way+='<div class="dir">'+count+'. '+dir+'</div>'+'<div class="results"><div class="time">'+time+'</div><div class="dist">'+dist+'</div>'+end; but I can't figure out what that "last loop" code should be. Any ideas? |