JavaScript - Simple Javascript Loop
Hi guys
I have what i think is a fairly simple script used for an image gallery with a next and back button. It seems to work pretty well, but i would like to make the gallery scroll round... ie when the user reaches the last picture and presses the next button again, the first image will be displayed again - and visa versa with the first image and the back button. Below is my JS, can post the small amount of HTML that calls it if necessary. Any help MUCH appreciated, been messing around with it for ages and being the newbie i am, can't seem to find any way of doing it Code: // List image names without extension var myImg= new Array(6) myImg[0]= "performance2011"; myImg[1]= "performance2005"; myImg[2]= "performance2006"; myImg[3]= "performance2007"; myImg[4]= "performance2008"; myImg[5]= "performance2009"; myImg[6]= "performance2010"; // Tell browser where to find the image myImgSrc = "../images/"; // Tell browser the type of file myImgEnd = ".jpg" var i = 0; // Create function to load image function loadImg(){ document.imgSrc.src = myImgSrc + myImg[i] + myImgEnd; } // Create link function to switch image backward function prev(){ if(i<1){ var l = i } else { var l = i-=1; } document.imgSrc.src = myImgSrc + myImg[l] + myImgEnd; } // Create link function to switch image forward function next(){ if(i>5){ var l = i } else { var l = i+=1; } document.imgSrc.src = myImgSrc + myImg[l] + myImgEnd; } // Load function after page loads window.onload=loadImg; Similar TutorialsThis 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> 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... / I have the following code: Code: if (n==1 && g <=5) { sndPlayer1.URL ="Boy-a1.wav"; } else if (n==1 && g >5) { sndPlayer1.URL ="Girl-a1.wav"; } else if (n==2 && g <=5) { sndPlayer1.URL ="Boy-e1.wav"; } else if (n==2 && g >5) { sndPlayer1.URL ="Girl-e1.wav"; } else if (n==3 && g <=5) { sndPlayer1.URL ="Boy-i1.wav"; } else if (n==3 && g >5) { sndPlayer1.URL ="Girl-i1.wav"; } else if (n==4 && g <=5) { sndPlayer1.URL ="Boy-o1.wav"; } else if (n==4 && g >5) { sndPlayer1.URL ="Girl-o1.wav"; } else if (n==5 && g <=5) { sndPlayer1.URL ="Boy-u1.wav"; } else if (n==5 && g >5) { sndPlayer1.URL ="Girl-u1.wav"; } else if (n==6 && g <=5) { sndPlayer1.URL ="Boy-b1.wav"; } else if (n==6 && g >5) { sndPlayer1.URL ="Girl-b1.wav"; } else if (n==7 && g <=5) { sndPlayer1.URL ="Boy-b1.wav"; } else if (n==7 && g >5) { sndPlayer1.URL ="Girl-b1.wav"; } else if (n==8 && g <=5) { sndPlayer1.URL ="Boy-h1.wav"; } else if (n==8 && g >5) { sndPlayer1.URL ="Girl-h1.wav"; } else if (n==9 && g <=5) { sndPlayer1.URL ="Boy-t1.wav"; } else if (n==9 && g >5) { sndPlayer1.URL ="Girl-t1.wav"; } I was wondering what the best way to make a smaller simpler version of this code is? Would it be using a loop? If so can you help me with how to Code: <script> var rXL = ""; do { rXL = prompt("Enter more entries? Y/N"); // IF Y or N is entered, the loop should in theory exit } while (rXL != "Y" || rXL != "N"); </script> IF Y or N is entered, the above loop should in theory exit, however it results in a infinite loop :/. Does anyone know what I'm doing wrong? Thank you all . 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; } } 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 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 Hi Chaps, I have a PHP loop script that returns Job Information for each Project. What I've got so far is an Export to Excel (2007) function that displays the Project information on 1st tab, and the Job information on the 2nd. The problem I've got is that the Export to Excel function, gathers the information from the HTML table ID, but when looping through the data (resulting in more than 1 Job for a Project), the only way I can differentiate is to use some PHP code, something like: Quote: id="tbl_job_<?php echo $job_id; ?>" What I basically want is to store the information for each Job on a different Excel tab. But whart I have seems to break the javascript: Code: <script language="javascript" type="text/javascript"> function ExportToExcel() { var xlApp = new ActiveXObject("Excel.Application"); // Silent-mode: xlApp.Visible = true; xlApp.DisplayAlerts = false; var xlBook = xlApp.Workbooks.Add(); xlBook.worksheets("Sheet1").activate; var XlSheet = xlBook.activeSheet; XlSheet.Name="Project"; // Store the sheet header names in an array var rows = tbl_project.getElementsByTagName("tr"); var columns = tbl_project.getElementsByTagName("th"); var data = tbl_project.getElementsByTagName("td"); // Set Excel Column Headers and formatting from array for(i=0;i<columns.length;i++){ XlSheet.cells(3,i+1).value= columns[i].innerText; //XlSheetHeader[i]; } //run over the dynamic result table and pull out the values and insert into corresponding Excel cells var d = 0; for (r=4;r<rows.length+3;r++) { // start at row 2 as we've added in headers - so also add in another row! for (c=1;c<columns.length+1;c++) { XlSheet.cells(r,c).value = data[d].innerText; d = d + 1; } } //autofit the columns XlSheet.columns.autofit; xlBook.worksheets("Sheet2").activate; var XlSheet2 = xlBook.activeSheet; XlSheet2.Name="Job"; // Store the sheet header names in an array var rows = tbl_job.getElementsByTagName("tr"); var columns = tbl_job.getElementsByTagName("th"); var data = tbl_job.getElementsByTagName("td"); // Set Excel Column Headers and formatting from array for(i=0;i<columns.length;i++){ XlSheet2.cells(3,i+1).value= columns[i].innerText; //XlSheetHeader[i]; } //run over the dynamic result table and pull out the values and insert into corresponding Excel cells var d = 0; for (r=4;r<rows.length+3;r++) { // start at row 2 as we've added in headers - so also add in another row! for (c=1;c<columns.length+1;c++) { XlSheet2.cells(r,c).value = data[d].innerText; d = d + 1; } } //autofit the columns XlSheet2.columns.autofit; // Make visible: xlApp.visible = true; xlApp.DisplayAlerts = true; CollectGarbage(); //xlApp.Quit(); } </script> This is the bit I think I need to change to get the JS to work, but I'm a bit out of my depth! Quote: xlBook.worksheets("Sheet2").activate; var XlSheet2 = xlBook.activeSheet; XlSheet2.Name="Job"; // Store the sheet header names in an array var rows = tbl_job.getElementsByTagName("tr"); var columns = tbl_job.getElementsByTagName("th"); var data = tbl_job.getElementsByTagName("td"); Any helpor guidence would be awesome! Trying to use a "for" loop to cycle through an array and compare values; if the values are equal, then it displays a message about the team, etc. Code: <html> <head> <title>Javascript Colors!</title> <script type="text/javascript"> var teamcolors = ["blue","orange","Auburn Tigers","Yuck!","black","red","Georgia Bulldogs","Congratulations!","yellow","black","Georgia Tech","Awesome!"] function changeBGColor() { document.body.bgColor = prompt("What color should the background be?","Put ANY color here!"); checkForTeamColors(); } function changeTXTColor() { document.getElementById("text").style.color = prompt("What color should the text be?","Put ANY color here!"); checkForTeamColors(); } function checkForTeamColors() { var bgcolor = document.body.bgColor var txtcolor = document.getElementById("text").style.color var loopcount = 1 while (loopcount <= 12) { if ( (bgcolor == teamcolors[loopcount] && txtcolor == teamcolors[loopcount + 1]) || (bgcolor == teamcolors[loopcount + 1] && txtcolor == teamcolors[loopcount]) ) { alert("You have picked the team colors of " + teamcolors[loopcount + 2] + ". " + taemcolors[loopcount+3]) } loopcount = loopcount + 4; } } </script> </head> <body> <p id="text" align="center">This text will change color if you want to. <br> Maybe try a certain combination, like Orange and Blue, or Red and Black?<br></p> <button onClick="changeBGColor()">Click me to change the BG Color!</button> <button onclick="changeTXTColor()">Click me to change the text Color!</button> <p id="variables"></p> <script type="text/javascript" document.getElementById("variables").innerHTML = ( bgcolor + " " + txtcolor ) </body> </html> Hey all, I need help creating a Javascript loop which posts a single static comment to all videos on a website(unless another language would prove to be a better alternative?) I'm not sure where to start and although I have an idea, my lack of programming skills have left me to turn to forums...any help would be greatly appreciated. *not asking for coding necessarily. Links to relative information pertaining to such a program/"loop", and any comments helping me understand what I'm trying to do would be great...I'm just not sure what to search for lol. Im still learning, just need helping starting a project. Thanks. What I am trying to do is when a user click on an image button, 10 new windows will oppen. So, I created a For Loop function for that. Here is my code below: function clickk () { for (i=0; i<=10, i++) { window.open('annoying1.html','Annoying LOL','width=900, height=900') ;} } However, the window does open but not 10 times. Can you help me? Thank you... I want to submit form using javascript but as I see javascript doesn't work in php loop. I use this code: Code: <form name="theForm"> <input type=text name="formInput"> <a href="javascript:document.theForm.submit();">Submit</a> </form> and it works fine in ordinary page, but stops working in php loop! I need to use link, not button to submit form. Can anyone please help? Thanks in advance I have done a basic while loop code but I can not figure out how to make the output print in 4 lines containing 5 numbers each. Can anyone tell me how to specify the number of output that appears on each line? Code: <?xml version="1.0" encoding="UTF-8"?> <!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> <title>example</title> </head> <body> <script type="text/javascript"> <!-- var x = 1; var linebreak="<br/>" while (x <= 20) { document.writeln("" + x + " " + ""); x = x + 1; } // --> </script> </body> </html> i, Am developing a webform using PL/SQL. Am using javascript to do some form validation Sample if(a =="") { alert("Please enter the first name"); return false; } else if(b =="") { alert("Please enter the last name"); return false; } else if (y !="Test1") { if (y != "Test2") { if (y != "Test3") { alert("Enter the right text"); return false; } } alert("am wrong outside"); } else if(z =="") { alert("Please fill al the fields"); return false; } it passes till alter("am wrong outside") and executes the procedure but doesnt goes to the last else part. I want it to go the last else part too. Please help. I am using the counter script below to display a count from 1-36. Does anyone know how to edit the javascript to flash or blink the number 36 a few times, and then loop the script to start over and count from 1-36 again (and again)? Here's the script: <html> <head> <title></title> </head> <script type="text/javascript"> var t, max, i; function Increase(amount) { max = amount; i = parseInt(document.getElementById("count").value); t = setInterval("SetIncrease()", 500); } function SetIncrease() { document.getElementById("count").value = ++i; if(i == max) { clearTimeout(t); } } </script> <body onLoad="Increase(36);"> <input id="count" type="text" value="1" style="width:40px;font-family:georgia;font-size:30px;font-weight:bold;color:#CC0000;border: 0px solid #000000;text-align:right;background-color:#FFFF00;" align="center"> </body> </html> Many thanks! I have the following code...the getelementbyId works fine it changes the value in the textfield aswell....but only in the first retrieved record...It is not working in any of the other records that are showed. Code is he <?php include("../connection/conn.php"); ?> <script type="text/javascript"> function notEmpty(){ var myTextField = document.getElementById('myText'); document.getElementById('myText').innerHTML = myTextField; if(myTextField.value != "") alert("You entered: " + myTextField.value) else alert("Would you please enter some text?") } </script> </head> <body> <?php $sql=mysql_query("select * from menuscript"); while($row=mysql_fetch_array($sql)) { ?> <div class="mine"> <?php echo $row['author'];?> <form> <input type='text' id='myText' /> <input type='button' onclick="notEmpty();" value='Form Checker' /> </form> </div> <?php }?> i know there are pre-made scripts to do what i'm doing. i want to create this myself to learn. i'm trying to create a list of section titles with arrows next to them, clicking on an arrow expands the section to read it's text, clicking on the arrow again collapses the section text. additionally, i would like an "expand all" and "collapse all" link and that's where my issue baffles me. my js - Code: function expandAll() { var collapsedDivs = document.getElementsByClassName('collapsed'); for (var i=0; i<collapsedDivs.length; i++) { var expandMe = collapsedDivs[i]; expandMe.style.display = 'block'; expandMe.addClassName('expanded'); expandMe.removeClassName('collapsed'); document.getElementById('arrow_'+i).innerHTML = '<img src="../media/hide.gif" />'; } } my html - Code: <div style="float:left" id="arrow_0"><img src="../media/show.gif" /></div><div style="margin-left:20px; text-align:left; font-weight:bolder; font-size:14px">SECTION ONE TITLE</div> <div class="collapsed" style="margin-left:20px; margin-right:30px; text-align:left; display:none">Section one text text text text text text text text text text text text text text text text text text text text text text </div> <div style="float:left" id="arrow_1"><img src="../media/show.gif" /></div><div style="margin-left:20px; text-align:left; font-weight:bolder; font-size:14px">SECTION TWO TITLE</div> <div class="collapsed" style="margin-left:20px; margin-right:30px; text-align:left; display:none">Section two text text text text text text text text text text text text text text text text text text text text text text </div> <div style="float:left" id="arrow_2"><img src="../media/show.gif" /></div><div style="margin-left:20px; text-align:left; font-weight:bolder; font-size:14px">SECTION THREE TITLE</div> <div class="collapsed" style="margin-left:20px; margin-right:30px; text-align:left; display:none">Section three text text text text text text text text text text text text text text text text text text text text text text </div> <div style="float:left" id="arrow_3"><img src="../media/show.gif" /></div><div style="margin-left:20px; text-align:left; font-weight:bolder; font-size:14px">SECTION FOUR TITLE</div> <div class="collapsed" style="margin-left:20px; margin-right:30px; text-align:left; display:none">Section four text text text text text text text text text text text text text text text text text text text text text text </div> upon executing the function, the result is the text for sections one and three being expanded and the arrows for one and two being changed. why? what am i doing wrong? I have am currently taking over as the developer for this web site, and the developer who left the project unfinished wrote a script. What it does is takes posts from vBulletin forums, for instance News posts, and then it grabs the posts by ID and Title and writes the title on the home page of the web site. The problem right now that I have is the test wraps, you can see what I mean here http://www.netcodeilluminati.com/v2 If you look on the left, I want to make the text cut off after a certain amount of characters with "..." at the end as if there is more to the title but you can't see it. Here is the script: for (x = 0; x < 5; x++) { document.write("<li><div class=\"li_icon\"><img src=\"images/icons/text.png\" alt=\"text\" /></div><div class=\"li_text\">"); document.write("<a href=\"../forums/showthread.php?t="+threads[x].threadid+"\">"+threads[x].title+"</a></div></li>"); } I was wondering how I could go about doing this. Thanks for any future help. -Kevin |