JavaScript - Maybe A For...in Loop Bug - I Can't Find It!!!
This is a function designed to return an array of all elements in "body" with a particular tag name and class name. It works fine up until the if (needles.length == 0); { line, according to my debugging. It seems to fail there though and I can't figure out why. It's probably just some noob error that I've missed but I can't for the life of me find it
Thanks in advance for any help, it's greatly appreciated! Code: function getElementsByClassName(tagname, classname) { var haystack = document.getElementById('body').getElementsByTagName(tagname); var needles = []; var i; for (i in haystack) { if (haystack[i].hasClassName(classname)) { needles.push(haystack[i]); continue; } } if (needles.length == 0); { needles = 0; } return needles; } Similar TutorialsOk, I'm nearly pulling my hair out with this one. I have been looking at this code for two evenings now, and rewrote it 4 times already. It started out as jQuery code and now it's just concatenating strings together. What I'm trying to do: Build a menu/outline using unordered lists from a multidimensional array. What is happening: Inside the buildMenuHTML function, if I call buildMenuHTML, the for loop only happens once (i.e. only for 'i' having a value of '0'.) If I comment out the call to itself, it goes through the for loop all 3 times, but obviously the submenus are not created. Here is the test object: Code: test = [ { "name" : "Menu 1", "url" : "menu1.html", "submenu" : [ { "name" : "menu 1 subitem 1", "url" : "menu1subitem1.html" }, { "name" : "menu 1 subitem 2", "url" : "menu1subitem2.html" } ] }, { "name" : "Menu 2", "url" : "menu2.html", "submenu" : [ { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" }, { "name" : "menu 2subitem 1", "url" : "menu2subitem1.html" } ] }, { "name" : "Menu 3", "url" : "menu3.html", "submenu" : [ { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" }, { "name" : "menu 3 subitem 1", "url" : "menu3subitem1.html" } ] } ]; Here is the recursive function: Code: function buildMenuHTML(menuData,level) { var ul; if (level == 1) { ul = "<ul id='menu'>"; } else { ul = "<ul class='level" + level + "'>"; } for (i = 0; i < menuData.length; i++) { menuItemData = menuData[i]; ul += "<li>"; ul += "<a href='" + menuItemData.url + "'>" + menuItemData.name + "</a>"; if (typeof menuItemData.submenu != 'undefined') { ul += buildMenuHTML(menuItemData.submenu,level + 1); } ul += "</li>"; } ul += "</ul>"; return ul; } Here is how the function is called initially: Code: buildMenuHTML(test,1); This is it's return value (with indentation added for readability): Code: <ul id='menu'> <li><a href='menu1.html'>Menu 1</a> <ul class='level2'> <li><a href='menu1subitem1.html'>menu 1 subitem 1</a></li> <li><a href='menu1subitem2.html'>menu 1 subitem 2</a></li> </ul> </li> </ul> 'Menu 2' and 'Menu 3' don't show up! I'm sure it's something small that I'm overlooking, but any help would be appreciated. Hi all I'm well aware that I can't post assignments here and expect an answer, however, I have been staring at this code for so long. I feel I am close to the solution (to get the correct output to the browser) but I just cannot get it to count how many moves it takes. I don't want an answer, but a nudge in the right direction would be very grateful. As you can see from the code and the output, it will attempt to write to the browser how many moves, but only '0'. Code: function rollDie() { return Math.floor(Math.random() * 6) + 1; } /* *searches for a number in a number array. * *function takes two arguments * the number to search for * the number array to search *function returns the array index at which the number was found, or -1 if not found. */ function findIndexOf(number, numberArray) { var indexWhereFound = -1; for (var position = 0; position < numberArray.length; position = position + 1) { if (numberArray[position] == number) { indexWhereFound = position; } } return indexWhereFound; } //ARRAYS that represent the board -- you do not need to change these //array of special squares var specialSquaresArray = [1,7,25,32,39,46,65,68,71,77]; //array of corresponding squares the player ascends or descends to var connectedSquaresArray = [20,9,29,13,51,41,79,73,35,58]; //VARIABLES used -- you do not need to change these //the square the player is currently on var playersPosition; //play is initially at START playersPosition = 0; //what they score when they roll the die var playersScore; //the index of the player's position in the special squares array or -1 var indexOfNumber; //MAIN PROGRAM //TODO add code here for parts (iii), (iv)(b), (v), and (vi) // start of question(iii) playersScore = rollDie(); document.write(' Sco ' + playersScore); playersPosition = playersScore + playersPosition; document.write(', Squa ' + playersPosition); indexOfNumber = findIndexOf(playersPosition, specialSquaresArray); if (indexOfNumber != -1) { document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber]); playersPosition = connectedSquaresArray[indexOfNumber]; indexOfNumber = -1; } document.write('<BR>') // end of question(iii) // start of question(iv)(b) while(playersPosition<=80) { playersScore = rollDie() document.write(' Sco ' + playersScore) playersPosition = playersPosition + playersScore document.write(', Squa ' + playersPosition) indexOfNumber = findIndexOf(playersPosition, specialSquaresArray) if(indexOfNumber != -1) { document.write(', Ladder to Squa ' + connectedSquaresArray[indexOfNumber]); playersPosition = connectedSquaresArray[indexOfNumber]; } document.write('<BR>'); } var countMoves = 0; while(countMoves <= 0) { document.write('You took ' + countMoves + ' moves to get out'); countMoves = countMoves + 1 } /*for (var countMoves = 0; countMoves < playersPosition; countMoves = countMoves + 1) { countMoves = countMoves + playersPosition; document.write('You took ' + countMoves + ' moves to get out'); }*/ // end of question(iv)(b) // start of question (v) /*if (playersPosition >=80) { document.write('The player is out'); }*/ // end of question (v) </SCRIPT> </HEAD> <BODY> </BODY> </HTML> Many thanks. Hello... Thanks for reading... I am getting an undefined error when i try to get a value from this array in the interior loop... Code: // This is the array I am trying to access AuditTable [0] = ["Visio Modifed date","Word Modified Date","User Status","User Comment","Last Audit","Audit Status","Audit Comment"] AuditTable [1] = ["11/23/2009 8:52:18 AM","missing","OK","user comment number 1","1/1/2009","ok","audit comment number 1"] AuditTable [2] = ["11/24/2009 12:21:19 AM","missing","Out of Date","Changes from 2008 not implemented","1/2/2009","Out of Date","needs update"] AuditTable [3] = ["11/22/2009 9:24:42 PM","missing","Incomplete","Document doesnt cover all possibilities","1/3/2009","Inadequate","needs update"] I have hard coded values and had success such as: Code: data = AuditTable[1][0] But when I put the vars associated with the loop in I get an undefined error - AuditTable[i] is undefined: Code: // produces error data = AuditTable[i][j] //Works but retrieves wrong data data = AuditTable[j][i] //Works but retrieves wrong data data = AuditTable[1][i] //Works but retrieves wrong data data = AuditTable[j][2] I must be trying to access the array incorrectly or something... I have defined all the vars, and tried many combinations, alerted the values of both vars so I can prove it is not a scope issue... Am I missing something obvious? Thanks much... Code: var reportArray=new Array(); var reportData, title, subTitle, data; for(i in parmarray)// loop thru AuditTable array and get values { title = '<div style="font-family:verdana; font-size:14px; font-weight:bold; margin:25px 0px 5px 30px">'; title += namearray[i][0]; title += '</div>'; reportArray.push(title);//Take compiled variable value and put it into array for(j=0; j < AuditTable[0].length; j++)// loop thru AuditTable array and get values { subTitle = AuditTable[0][j];//points to first row of AuditTable where the labels are data = AuditTable[1][0];//points to the current row where actual data is html = i + j +'<div style="font-family:verdana; font-size:12px; color:#696969; font-weight:bold; margin-left:30px;">'; html += subTitle; html += '</div><div style="font-family:verdana; font-size:12px; color:#a9a9a9; margin-left:30px; margin-bottom:10px">'; html += data; html += "</div>"; reportArray.push(html);// put results into array } } it wont loop, as long as you enter something in the name field it will submit. also how do i stop from submitting if all fields are not filled out? any help will be appreciated) ====== function checkForm(form) { var len = form.elements.length; var h=0; for (h=0; h<=len; h++){ if ((form.elements[h].value==null) || (form.elements[h].value=="")){ alert("Please enter "+document.myForm.elements[h].name); document.myForm.elements[h].focus(); return false; } return true; } } ===body-== <FORM NAME="myForm" METHOD="post" ACTION="http://ss1.prosofttraining.com/cgi-bin/process.pl"> Name:<BR> <INPUT TYPE="text" size="30" NAME="name"><br> Email address:<BR> <INPUT TYPE="text" size="30" NAME="email address" onBlur="emailTest(this);"><br> Phone number:<BR> <INPUT TYPE="text" size="30" NAME="phone number"><br> Fax number:<BR> <INPUT TYPE="text" size="30" NAME="fax number"><p> <INPUT TYPE="submit" VALUE="Submit Data" onClick="return checkForm(this.form);"> <INPUT TYPE="reset" VALUE="Reset Form"> </FORM> Hi, I am doing some studying and we was to create a small loop using either the for loop, while loop or do while loop. I chose to do the for loop because it was easier to understand, but I want to know how to do the same using the while loop. Here is the for loop I have, but I cant figure out how to change to while loop. Code: for (var i = 0; i < 5; ++i) { for (var j = i; j < 5; ++j) { document.write(j + ""); } document.write("<br />"); } output is equal to: 01234 1234 234 34 4 How do you make the same using a while loop? This is the script itself - no error messages are generated. Code: <script language="javascript" type="text/javascript"> function getXMLHTTPRequest() { try { req = new XMLHTTPRequest(); } catch(err1) { try { req = new ActiveXObject("Msxm12.XMLHTTP"); } catch(err2) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(err3) { req = false; } } } return req; } var http = getXMLHTTPRequest(); function getCattle(animal_id){ var myurl = 'find_cattle.php'; var CattleValue=animal_id; var modurl= myurl+"?d="+CattleValue; **************the alert returns the correct value from my selection and after than nothing, I never get my alert from the response portion alert("Looking For "+modurl); ******* http.open("GET", modurl, true); http.onreadystatechange=useHttpResponse; http.send(null); } function useHttpResponse(){ ************It never gets to this response alert("Made It To Response"); if (http.readyState == 4) { if(http.status == 200) { var ListValue = http.responseXML.getElementsByTagName("animal_id")[0]; document.getElementsById('cattle_data').innerHTML = animal_id.childNodes[0].nodeValue; } } } </script> thank you Hello. Please excuse my ignorance but I am not too clued up on javascript. Im hoping someone may be able to help me out here. I have managed to locate a script which will find text on a page, but I have a couple of requests. Firstly the script will only search up. I would like the search box to be at the top of a page but the only way to get it to work correctly is placing it at the bottom of the page. Secondly would some kind soul advise me how to place the script in an external file and then link to it. Thanks in advance. Hello, Below is the javascript I'm debugging (or trying to) but just can't see where the error is: The code should send a message "GOOODDD!!!" when the input box is empty (nothing typed in) and should send a message (BAAADD!!!) when a string of theee a's are typed in ("aaa"). The problem is that no matter what I type in the script ALWAYS sends me a "GOOODD!!" message. I guess it is a simple glitch but I just can't figure it out. I'd appreciate any help Thank You. Code: <script language="javascript" type="text/javascript"> <!-- function textCheck(that) { var mytext=document.getElementById("BLABLA") if (mytext == "aaa") alert("BAAAAADDDDD!!!!" + mytext.value); else alert(" GOOOODDDD!!!!" + mytext.value); } --> </script> </head> <body> <form id="form1" method="get" onsubmit="textCheck(this)" /> <input name="BLABLA" size="3" type="text"/> Input Data <br/><br/> <input name="Submit1" type="submit" value="submit" /> </body> </html> function textSize(updown) { var size = Number(readCookie('user-font-size')); if (size == 0) { size = 12; // No Cookie, Set A Default Size Of 12px } size = size + Number(updown); // Adjust The Current Size if (size > 20) { size = 20; } // Stop At 13 if (size < 12) { size = 12; } // Stop At 10 writeCookie('user-font-size', size, 12); // Update The Cookie document.body.style.fontSize = size + 'px'; // Set The Users Text Size } function writeCookie(name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = '; expires=' + date.toGMTString(); } else { expires = ''; } document.cookie = name + '=' + value + expires; } function readCookie(name) { name += '='; var cs = document.cookie.split(';'); for (var i = 0; i < cs.length; i++) { var c = cs[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(name) == 0) { //-----------// return c.substring(name.length, c.length); // Gotcha // } //-----------// } //------------// return null; // Failed // } //------------ <img id="plustext" class="zoom-in" alt="Increase text size" src="Zoom-In-icon.png" onclick="textSize (2);" style="cursorointer" /> <img id="minustext" class="zoom-out" alt="Decrease text size" src="Zoom-Out-icon.png" onclick="textSize (-2);" style="cursorointer" /> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vel fringilla arcu. Cras ullamcorper nunc ac sapien gravida ultrices. Curabitur mollis consectetur elit non tempus. Duis blandit luctus feugiat. Nullam eget tellus at quam dapibus tempus in scelerisque ligula. Phasellus turpis ante, tincidunt at aliquam vel, luctus vitae leo. Suspendisse dignissim vehicula est, ac dapibus justo pellentesque eu. </p> cheers hope thats enough code Ant. hi I need to find the average number in javascript. I have been working on it for a while but i am getting no where yes i am new to javascript and to be honest it is doing my blonde headed brain in. can someone please take a look at it and advise me on what i am doing wrong. it is the only bit of javascript that i have to do in the course but it carries a high mark of which i can not afford to lose Any way the question is : "Write code to calculate the average height and write it out in the browser window" Code: <HEAD> <TITLE> average </TITLE> <SCRIPT LANGUAGE = "JavaScript"> //Experimental results of Table 1 stored in arrays. var Height = [15,16,17,18,19]; var Number = [2,1,6,4,2]; //Part (ii). //Write code to declare and initialise new array to represent the third row of the table. var avg = new Array(5) var avg = ["60","80","187","180","114"] ; avg[0] = "60"; avg[1] = "80"; avg[2] = "187"; avg[3] = "180"; avg[4] = "114"; //Part (iv). //Write code to calculate the average height and write it out in the browser window. avg = 0; for (var count = 1; count <= 5; count = count + 1) Array.average = function(){ var avg = 0; for(var a = 0; a < this.length; a++){ avg += this[a]; } return avg / this.length; }; document.write('average height is ' +avg + '<br>'); </SCRIPT> </HEAD> <BODY> </BODY> </HTML> sorry for my ignorance thanks in advance kelly XXXXX Hello, please tell me where can I find script visible on page www.frendzel.pl (Big picture changing every few second to another from the list on the left)
Hi, I've been trying to code a javascript fonction that uses Window.find and I'm having problems doing exactly what I want. I don't know much of java and I understand that it's not everyone who's willing to do all the work for me so I'm looking for a very kind person here I want it to find a specific string that won't change (so no use to prompt for it) in another existing page that would be loaded in a frame. When the string is found, a sound is played like an alarm. The entire thing should reload every like 5 minutes. That's the easy part. I'm having trouble with the "If found in the frame, play a sound part". I don't think it's pretty hard to do, but hey, I can't do it. As I said earlier, I understand I ask for someone to do the whole thing for me but I'm willing to pay by paypal for the service. Let's say... I don't know, ten bucks should do it. I think I've been clear with what I need but if not, please feel free to ask for more specifications. Thanks for your time. Hi All, I have the date in 2009-10-24 format.can anyone tell how can I get the day of any particular date entered by user. Thanks in advance... Hi all. Is it possible to command a find in page search from another html? I have a 'main page' and 'directory page' The directory page has find in page command on it, so if users can open the directory link from the main page and then search that page using the find in page search box. To speed this up, is there any way I can have a text box on my main page that when I enter text and submit that it carries across the text entry to the find in page box on the directory page and starts this search for me? I need to complete this using javascript so if this is possible I would great appreciate any help. Thanks Hello, I have recently started a website which tells visitor's IP address, location and others details. I want to add some more functions to it. I found no way to detect visitors Internet Service Provider (ISP) using PHP. I would like to know if there is any way to do so in Javascript. Click the below link to view the site: Show IP Please help me ASAP. Regards, Wasif K. Hi All, Just a quick question! Is it possible to have a text box input searching for the entered text on another webpage in the same way Find In Page would do? I have a webpage that I want users to input an item, and that this will open the targeted webpage and bring you to (and highlight) the matched item(s) like find in page does. Is this possible or is the easiest way to just make users open the link to the target page and just complete the find in page search there? Thanks Glen I was trying to sum every number in the array and I wrote this function: Code: function sumArray(array) { var total = 0, i; for (i = 0; i <= array.length - 1; i++) { if(typeof array[i] == "number") { array[i] += total; } } return total; } I don't know why but it always returns "0". In other words, the initial value of "total" (if it was 5, it returns 5 etc...). I really can not see what is wrong here, any suggestions? I need some help finding a "find on page" script that will display the results in the middle of the page for IE. I have tried several different ones to no avail. The ones that work in all the browsers display the result in IE at the very bottom of the page. I am not very familiar with programing in Java and I am unable to modify any for my needs. The one I found that did work in IE didn't work in any other browsers. Please help, Thx
Hi Guys & Girls, I am looking for help with a technical issue, which my programmer can't find the answer to. My website has a demonstration facility which allows a client to enter their website which then in turn creates a video transparency overlaying their own website. The problem is some sites with Flash, overlay my transparency video so that you cant see my demo video. Any ideas please. Thanks Maximillion |