JavaScript - Simple Loop Does Not Behave Right!
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... / Similar TutorialsHi 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: <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 . 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 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; } } Ok, for starters I'm not a beginner and my website is running under standards mode (not quirks). When my site loads I perform: Code: window.location.replace(window.location.href + "#encodedstuff"); The effect being that no new history points are created and the very first history point now includes some encoded info in the hash. When the user closes and relaunches IE8 and then chooses "reopen last browsing session" I expect IE to make the request for the page including the hash value. It does NOT! It simply makes the request for the URL without the hash (and then adds the hash as the next history point). I need help figuring out why and if there is a way to accomplish this without needing to add a parameter to the location get request (which will cause my site to reload upon launch if this parameter is not already set... I don't want it doing that). Please note that the browser DOES behave if I copy the new URL, including the hash value and paste it into a new tab (closing the old tab). When I relaunch IE8 and reopen the previous session it does make the request with hash value and my site is able to get the required info out of the hash. It only fails for a tab that initially did not have a hash and my script performs the above location.replace. Solving this is critical for my application, so I seriously appreciate any help! Hi all I have created a website http://www.clickmunki.com with a jQuery vertical panel that collapses and expands in the top left of each page. In my offline code (which I have not yet uploaded to the live site) I have set the panels to display by default so the user automatically has the information available to them on each page as they scroll through the site. My problem is that the panels are not behaving independently of each other. When one panel is collapsed then they all collapse instead of just the one that the user has clicked. This is my first attempt at using javascript and jQuery and I am not sure how to resolve this. Any assistance would be very much appreciated. This is my js: Code: $(document).ready(function(){ $(".trigger").click(function(){ $(".panel").toggle("fast"); <! panel is for the panel on the home page --> $(this).toggleClass("active"); return false; }); $(document).ready(function(){ $(".trigger").click(function(){ $(".panel2").toggle("fast"); <! panel2 is for the panels in the body of the site --> $(this).toggleClass("active"); return false; }); Kind regards Anne So I wrote a script to slide various divs horizontally. It takes 2 seconds to start and then begins, sliding, then stops, then slides, until all four slides are shown, and the slides back to the first one. My issue is I have two buttons that should take over and kill the auto sliding. Also the script is giving me errors. That mastertimer, and loopertimer is not defined... Why is that? Here is the code Code: <script type="text/javascript">// <![CDATA[ function restartSlide(item){ item.style.left = parseInt(item.style.left) + 60 +'px'; var resetLooperSl = setTimeout(function(){restartSlide(item)},15); if(parseInt(item.style.left) >= 0){clearTimeout(resetLooperSl);return;} } function stopSlide(){ clearTimeout(loopTimer); } function animateSlide(element,limit,transition){ if(transition == "stop" && parseInt(element.style.left) > -2460){ limit = limit - 820; } else if(transition == "stop" && parseInt(element.style.left) <= -2460){ limit = limit + 820; stopSlide(); } element.style.left = parseInt(element.style.left) -20 + 'px'; if(parseInt(element.style.left)<= limit){ setTimeout(function(){animateSlide(element,limit,"stop")},4000); clearTimeout(MasterTimer); } var loopTimer = setTimeout(function(){animateSlide(element,limit,"flow")},15); } function autoSlide(){ var MasterTimer; var RestarterTime; var adContainer = document.getElementById('adwrap'); adContainer.style.left = '0px'; MasterTimer = setTimeout(function(){animateSlide(adContainer,0,"stop")},3000); RestarterTimer = setTimeout(function(){restartSlide(adContainer)},25000); } addEvent(window, 'load', autoSlide); function btnSlideNow(elem, incremental){ elem.style.left = parseInt(elem.style.left) + incremental + 'px'; setTimeout(function(){btnSlideNow(elem, incremental)},30) } function btnActions(elem){ var incremental; if(elem.id == 'btnAdLeft'){incremental = 30} else if(elem.id == 'btnAdRight'){incremental = -30} btnSlideNow(elem, incremental); } function adButtons(){ document.getElementById('btnAdLeft').onclick = function(){btnActions(this)} document.getElementById('btnAdRight').onclick = function(){btnActions(this)} } addEvent(window, 'load', adButtons); // ]]></script> Also I'd like to see how you experienced scripters would write this cleaner. I'd like to see that, as I am new to js. It would help me learn. thanks 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 Code: window.onload = initForms; function initForms(){ for(var i=0; i<document.forms.length; i++){ document.forms[i].onsubmit = function(){ return validForm(); } } } Hi, this is the first part of a long code and I have three questions wondering if anyone could help me.. 1. What is the benifit of having the above code with "window.onload" and "for loop" and loop through the forms if I only have ONE form in html? 2. What is this line of code "document.forms[i].onsubmit" saying? Does it mean "Execute function() when submit button within form[i] has been pressed?" 3. function() - Does this empty function mean "run every following function below"?? Thank you!! Hi all Is using the real form submit button a problem in any way? Can it actaully send a form when a person uses 'enter' in a text field. When I use this submit, it triggers my validation which is great. Code: <input type="submit" value="OnSubmit validate" /> However this way doesn't seem to trigger my validation although It may solve the above form send problem (if that realy exists). How do I get it to act the same as real submit so it will trigger validation like onsubmit above? Code: <input type="button" value="Send Feedback" onclick="this.form.submit()" /> LT does any of that make sense? all ideas helpful and appreciated Ok, 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 } } 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? 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> I imagine this would be very simple for someone who knows javascript. I want to have three fields. First field is "posted speed limit", second field is "actual speed" and third field will be the output field. All the script needs to do it subtract the posted speed from the actual speed and add a ZERO to the end; which is the amount of the speeding ticket. The minimum fine is $100, however. So, 5 miles over the speed limit would be $100 (minimum value) 15 miles over the speed limit would be $150 (add a zero) 35 miles over the speed limit would be $350. etc. I know very little Javascript, if anyone could help me out with this, I'd appreciate it. Thanks, Sean For those who read my other thread I finally scratched together the code to take a value from an XML file and add it to a select box as an option. Ofcourse it only does it once so I need to loop it. It's kinda complex though, here's a function line to add one option: addOption(document.people_form.People,name2,office2) And here's the code in the head: <script type="text/javascript"> //load xml file if (window.ActiveXObject){ var xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async=false; //Enforce download of XML file first. IE only. } else if (document.implementation && document.implementation.createDocument) var xmlDoc= document.implementation.createDocument("","doc",null); if (typeof xmlDoc!="undefined") xmlDoc.load("namedata.xml"); //Regular expression used to match any non-whitespace character var notWhitespace = /\S/ function getnames(){ //Cache "messages" element of xml file var nameobj=xmlDoc.getElementsByTagName("list")[0] //REMOVE white spaces in XML file. Intended mainly for NS6/Mozilla for (i=0;i<nameobj.childNodes.length;i++){ if ((nameobj.childNodes[i].nodeType == 3)&& (!notWhitespace.test(nameobj.childNodes[i].nodeValue))) { // that is, if it's a whitespace text node nameobj.removeChild(msgobj.childNodes[i]) i-- } } } if (typeof xmlDoc!="undefined"){ if (window.ActiveXObject) //if IE, simply execute script (due to async prop). getnames() else //else if NS6, execute script when XML object has loaded xmlDoc.onload=getnames } var name2=xmlDoc.getElementsByTagName("name")[0].firstChild.nodeValue; var office2=xmlDoc.getElementsByTagName("office")[0].firstChild.nodeValue; var officePH2=xmlDoc.getElementsByTagName("officePH")[0].firstChild.nodeValue; var mobile2=xmlDoc.getElementsByTagName("mobile")[0].firstChild.nodeValue; var email2=xmlDoc.getElementsByTagName("email")[0].firstChild.nodeValue; </script> <script type="text/javascript"> function addOption(selectbox,text,value ) { var optn = document.createElement("OPTION"); optn.text = text; optn.value = value; selectbox.options.add(optn); } </script> Could anyone give me a pointer on how to loop this so that it loads one option after another from the XML file? Thanks. Hi All, im trying to to use a for loop to loop through a drop down list of users and if there is a match between the user logged in and the drop down list i want to enable two fields, if the user logged in isnt in the drop down list i want to disable the two fields, but im having trouble looping through, iv tried ".value" with no avail.. heres my Script Code: var RequestingUser = document.getElementById('JoinersLeaversContent_cmbRequestingUser').text; var Authorisers = document.getElementById('JoinersLeaversContent_ddlAuthoriseId'); for (var i = 0; i < Authorisers.length; i++) { if (RequestingUser.text == Authorisers.value) { document.getElementById('JoinersLeaversContent_txtAuthoriserSig').disabled = false; document.getElementById('JoinersLeaversContent_txtDateSignedOff').disabled = false; } else { document.getElementById('JoinersLeaversContent_txtAuthoriserSig').disabled = true; document.getElementById('JoinersLeaversContent_txtDateSignedOff').disabled = true; } } So just to be clear, if the user logged in appears in the drop down box i want to enable the two fields, if they dont appear i want to disable the two fields Please help. Thank you Hello all. I am faitly new at programming and have run into a little problem. I want to create a script that creates 2 random numbers, stored in 2 different variables and then compare them to eachother. there is two possible outcome of that comparison, either they are different or they are alike. If they are different i want to randomize a new set or numbers and make a other comparement, also to keep track on how many times i have created numbers. If they are alike i want to display the numbers and how many tries it took to get a matching pair. atm it looks like this <html> <body> <script> var x=(Math.floor(Math.random()*6)+1); var y=(Math.floor(Math.random()*6)+1); //creates two random int between 1 and 6 var throws = 1; //keep tabs on how many times we have thrown the dices if(x!=y) { x=(Math.floor(Math.random()*6)+1); y=(Math.floor(Math.random()*6)+1); throws=throws+1 }else{ document.write("you have rolled a pair. Dice 1 is: " +x +" and Dice 2 is: " +y +" and it took " +throws +" tries to get a pair."); } </script> </body> </html> How to get that into a loop? a really confused newbie scripter |