JavaScript - Can I Make An Array Inside A Loop?
Hi,
I have this loop: Code: for (var j = 0; j < gmarkers.length; j++) { gmarkers[j].hide(); elabels[j].hide(); map.closeInfoWindow(); var str=gmarkers[j].myname.toLowerCase(); var patt1=inp; if (str.match(patt1)) { found = true; gmarkers[j].show(); count++; var p=j; } } which was useful for passing the p variable when it was just one number. but now I need to get that number every time j gets set (I understand that the j gets overwritten each time the loop goes through). What would be ideal is if p could become an array, the contents of which match the values that j has passed though during the loop cycle. I thought var p = new Array (j); minght do the trick, but obviously not... I hope that I'm explaining it OK, and that it's possible, and that somebody has an idea how to do it... Similar TutorialsHi... I just want to know if it is possible to have an autocalculate in a textboxes inside while loop?and if it is possible how?.. here is my code: Code: <html> <head> <style type="text/css"> #fieldset_PS{ position: relative; width: 20%; } </style> <link rel="stylesheet" type="text/css" href="kanban.css" /> <script type="text/javascript"> function display_PS(){ document.loading_kanban.action="ParameterSettings.php"; document.loading_kanban.submit(); } function display_Kanban(){ document.loading_kanban.action="kanban_report.php"; document.loading_kanban.submit(); } </script> </head> <?php error_reporting(0); $con = mysql_connect('localhost', 'root',''); if (!$con) { echo 'failed'; die(); } mysql_select_db("mes", $con); ?> <form name="loading_kanban"> <div id="main_button"> <center> <!--<label style="margin-left: .9em; font-family: Arial, Helvetica, sans-serif; font-size: .7em;">Display Details:</label><input onclick='showDetails(this);' id='chkDetail' type='checkbox' checked='checked' value='wip'/> --> <input type="button" name="parameter_settings" value="Parameter Settings" onclick="display_PS()"> <input type="button" name="parameter_settings" value="Stock Requisition"> <input type="button" name="parameter_settings" value="Kanban Report" onclick="display_Kanban()"> </div> <div id="fieldset_PS"> <fieldset> <legend>Parameter Settings</legend> </center> <table border="1"> <th>Compounds</th> <th>Max</th> <th>Min</th> <?php $sql = "SELECT PCODE FROM parameter_settings ORDER BY PCODE ASC"; $result = mysql_query($sql, $con); while ($row = mysql_fetch_assoc($result)){ echo "<tr> <td>$row[PCODE]</td> <td><input type = 'text' name = 'max_pcode' size = '10'></td> <td><input type = 'text' name = 'min_pcode' size = '10'></td> </tr>"; } ?> </fieldset> </table> </div> </form> </html> I have table : parameter settings and i have fields: PCODE, max, min PCODE has data: PXX PYY PZZ PAA PBB Total I just want to know how can I auto calculate the total max and total min and it will display in the textbox beside Total... Thank you Hi, I hope someone can help me figure this out - it's been bugging me for a whole day now, and I can't seem to figure it out, and so far no Google research found this exact problem for me... Situation: I have a simple HTML page with one DIV element with the id "rotator". Inside that, JavaScript is supposed to create boxes that react to mouseovers. The weird thing is: The whole script works, but ONLY on the LAST box I create, no matter what I do. I can manually add the mouseover code to any one of these boxes, but it will only take on the last one. I can have JavaScript tell me the mouseover status of each box, and they all tell me they have code assigned correctly - but again only the last one works... Here's the relevant code (yes, highly abbreviated, but it's the part that fails on me): Code: var maxBoxes = 10; function initSite() { var rotator = document.getElementById("rotator"); rotator.innerHTML = ""; for (x = 0; x < maxBoxes; x++) { rotator.innerHTML +='<div id="myBox' + x + '"></div><div id="myDark' + x + '"></div>'; // various other stuff about myBoxes[x] also in here, but not relevant to the issue I think applyMouseActions(document.getElementById("myDark" + x); debugOutput(document.getElementById("myDark" + x).id+"=" + document.getElementById("myDark" + x).onmouseover + "<br>", 1); } } function applyMouseActions(item) { if (!item) return; item.onmouseover = function(ev) { alert("does this work?"); var thisNum = this.id; thisNum = thisNum.charAt(this.id.length-1); var tempBox = myBoxes[thisNum].boxOb; tempBox.style.background = "#fff"; } item.onmouseout = function(ev) { var thisNum = this.id; thisNum = thisNum.charAt(thisNum.length-1); var tempBox = myBoxes[thisNum].boxOb; tempBox.style.background = "#aaa"; } } initSite is called in the body onload. All kinds of other animation parts are implemented that work fine, just this mouseover won't work. I have tried re-writing it in multiple different ways, including "xyz.onmouseover = myMouseCode" and then defining the function separately later - still no dice. So, the code creates 10 boxes (0-9) and 10 boxes that are on top of them to create a form of shadow effect depending on the position of the original boxes. Since the "myDark" boxes are on top of the "myBox" boxes, I apply the onmouseover onto the "myDark" boxes, but it only works on "myDark9" and no other box. They are all created the same way, the mouseover assigned the same way... All I can do is shake my head at it, but that doesn't fix the issue, obviously ;-) Any idea what else I can try? Thanks! hi i'd like to ask how can i ask for a function inside a for loop , if i remove the loop the code works fine but i need it for 10 rows . please help , here is the code PHP Code: $content .=' <table cellspacing="2" cellpadding="2" border="0" align="center" > <SCRIPT LANGUAGE="JavaScript" type="text/JavaScript"> function doCalcAndSubmit() { // get both values kolicina1 = document.forms["vlez1"].kolicina.value; cena1 = document.forms["vlez1"].cena.value; // do some calculation vkupno1 = kolicina1 * cena1; // set the value in the right field document.forms["vlez1"].vkupno.value = vkupno1; } </script> <form id="vlez1" name="vlez1" method="POST" action="index_execute.php" > <tr valign="middle"> <td></td> <td align="center"><b> Sifra : </b></td> <td align="center"><b> Kolicina : </b></td> <td align="center"><b> Cena : </b></td> <td align="center"><b> Vkupno : </b></td> </tr> '; for($t=1;$t<11;$t++) { $content .= ' <tr valign="middle"> <td>'.$t.'.</td> <td><input type="text" id="sifra" autocomplete="off" name="sifra['.$t.']" align="middle" onblur="normalField(this);" onfocus="fireKeyListener_sifra(event); highlightField(this,1);" onkeyup="getList_sifra(event);" size="25" value="" /></td> <td><input type="text" id="kolicina" name="kolicina['.$t.']" align="middle" size="25" ></td> <td><input type="text" id="cena" name="cena['.$t.']" align="middle" size="25" onblur="doCalcAndSubmit();"></td> <td><input type="text" id="vkupno" disabled name="vkupno['.$t.']" align="middle" size="25" ></td> <input type="hidden" name="hidden_data" value="'.$data.'"> </tr>'; } $content .= '<tr> <td></td> <td></td> <td align="center"><input type="submit" id="submit2" name="submit2" value="Potvrdi" ></td> </tr> </form> </table> '; 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 Below is the code. My function: Code: function swap_content(id1,id2) { var tmp = document.getElementById(id1).name; var theval = document.getElementsByName('primary_propertyp_id')[0].value; document.getElementById(id1).name = document.getElementsByName('primary_propertyp_id')[0].name; document.getElementsByName('primary_propertyp_id')[0].name = tmp; document.getElementById(id2).id = document.getElementById('primary').id; document.getElementById('primary').id = 'addressid_'+theval+'_div'; } Applicable Code for primary info: Code: <div id="primary"> <label>primary to secondary:</label><input name="primary_propertyp_id" type="text" id="addressid_<? echo $row['primary_property_id']; ?>" value="<? echo $row['primary_property_id']; ?>"/> </div> Applicable Code for secondary info/link to change: Code: echo "<div id=\"addressid_" . $properties_row['id'] . "_div\">"; echo "<a href=\"#\" onclick=\"swap_content('addressid_" . $properties_row['id'] . "','addressid_" . $properties_row['id'] . "_div'); return false\">Make Primary</a>"; echo "<input id=\"addressid_" . $properties_row['id'] . "\" name=\"addressids[]\" value=\"" . $properties_row['id'] . "\" type=\"text\">"; echo "</div>"; This is running through a PHP loop so it's making multiple divs and links for the secondaries. I am wanting to be able to swap out any of them to make them 'primary'....this works for the first click, but after the first click it makes every div id and input name the same as the first that was clicked. It's also not working AT all if i click on the bottom link first, then a link above it. Top-down works, bottom-up doesn't...Please help Thanks in advance, Jeremy I need the rolling and the displaying in a loop and i am clueless. If anyone could help it would be much appreciated. <html> <head> <title> Die Rolls </title> <script type="text/javascript" src="http://balance3e.com/random.js"> </script> <script type="text/javascript"> function RollDice() { var roll1, roll2, roll3, roll4, roll5; roll1 = RandomInt(1, 6); roll2 = RandomInt(1, 6); roll3 = RandomInt(1, 6); roll4 = RandomInt(1, 6); roll5 = RandomInt(1, 6); document.getElementById('die1Img').src = 'http://balance3e.com/Images/die' + roll1 + '.gif'; document.getElementById('die2Img').src = 'http://balance3e.com/Images/die' + roll2 + '.gif'; document.getElementById('die3Img').src = 'http://balance3e.com/Images/die' + roll3 + '.gif'; document.getElementById('die4Img').src = 'http://balance3e.com/Images/die' + roll4 + '.gif'; document.getElementById('die5Img').src = 'http://balance3e.com/Images/die' + roll5 + '.gif'; document.getElementById('rollSpan').innerHTML = parseFloat(document.getElementById('rollSpan').innerHTML) + 1; } </script> </head> <body bgColor="lime"> <div style="text-align:center"> <p> <img id="die1Img" alt="die image" src="http://balance3e.com/Images/die1.gif"> <img id="die2Img" alt="die image" src="http://balance3e.com/Images/die2.gif"> <img id="die3Img" alt="die image" src="http://balance3e.com/Images/die3.gif"> <img id="die4Img" alt="die image" src="http://balance3e.com/Images/die4.gif"> <img id="die5Img" alt="die image" src="http://balance3e.com/Images/die5.gif"> </p> <input type="button" value="Click to Roll" onclick="RollDice();"> <hr> <p> Number of rolls: <span id="rollSpan">0</span> </p> </div> </body> </html> I am working on a site and in the process borrowed some js from some one to get dropdown menus to work, but after a while got reports from people who tested my site of some problems and decided to verify all my code, and i have fixed most bugs but the one listed in the title. Code: sfHover = function() { var sfEls = document.getElementById("nav").getElementsByTagName("LI"); for (var i=0; i<sfEls.length; i++) { sfEls[i].onmouseover=function() { this.className+=" sfhover"; }; sfEls[i].onmouseout=function() { this.className=this.className.replace(new RegExp(" sfhover\\b"), ""); }; } }; if (window.attachEvent) {window.attachEvent("onload", sfHover);} and i am verifying it on jslint the error i get is: Quote: Error: Problem at line 6 character 10: Don't make functions within a loop. }; Problem at line 9 character 10: Don't make functions within a loop. }; Implied global: sfHover 1,12, document 2, window 12 any help will be appreciated, and I'm sure this isn't complex but i don't know much js and want to keep it the same. Hello to all! How can I insert two values in an array in a salect option like the one below: Example: So I need in the "var op1 = new Option" an array thisarray[<?php echo"$user_name" ?>, <?php echo"$user_id" ?>] Data is being loaded by php from SQL Code: var newTextbox = document.createElement('select'); newTextbox.className = 'fn-select'; //First user in the populated select menu is the person Loged in var op1 = new Option("", ""); <----------[an array with two variables] ??? newTextbox.appendChild(op1); var txt1 = document.createTextNode('<?php echo"$user_name" ?>'); op1.appendChild(txt1); And then separate these variables and let the following function save them individualy: Code: function saveNote (note) { resetAjax(); var photoId = note.container.element.id; ajax.setVar('action', 'save'); ajax.setVar('photo_id', photoId); ajax.setVar('note_id', note.id); ajax.setVar('left', note.rect.left); ajax.setVar('top', note.rect.top); ajax.setVar('width', note.rect.width); ajax.setVar('height', note.rect.height); ajax.encVar('text', note.gui.TextBox.value); <------------- $user_name <------------- $user_id ajax.runAJAX(); var statusDiv = document.getElementById('PhotoNoteStatus'); ajax.onCompletion = function () {statusDiv.innerHTML = "<p>Note saved.</p>"; } return 1; } Hi, I am trying to search an array for a string and then if it is found alert it. I have found examples of how to iterate the array and how to use .IndexOf to return a true false statement as to whether the array includes the string, but i don't know what to do after that and how to display the string if its found. Any help appreciated.. Thanks Whats up guys, have an interesting one for you... So I have a pretty simple survey form, with 5 checkbox answers, one of them being "None of the Above". All 5 are part of the same question1[] array. My goal is to have a function that unchecks the other 4 boxes when None of the Above is checked. The problem is that since None of the Above is part of the question1 array, it unchecks itself. So how do I separate this None of the Above option? After all, it is still a valid answer to question 1, so I don't want it to sit in a different array just because... Here's what I have now: Java: Code: function SetValues(Form, CheckBox, Value) { var objCheckBoxes = document.forms[Form].elements[CheckBox]; var countCheckBoxes = objCheckBoxes.length; for(var i = 0; i < countCheckBoxes; i++) objCheckBoxes[i].checked = Value; } html: Code: <input id="question1" name="question1[]" type="checkbox" value="Answer 1"> 1<br> <input id="question1" name="question1[]" type="checkbox" value="Answer 2"> 2<br> <input id="question1" name="question1[]" type="checkbox" value="Answer 3"> 3<br> <input id="question1" name="question1[]" type="checkbox" value="Answer 4"> 4<br> <input id="question1" name="question1[]" type="checkbox" value="None of the above" onclick="SetValues('form1', 'question1[]', false);"> None of the above <br> So again the issue with this code is that since None of the Above is inside the question1 array, it unchecks itself as well. thanks, rg 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! 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 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 >< 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 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 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? 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 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 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> |