JavaScript - Javascript While Loop Question
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> Similar TutorialsHow do I re-write this from VBA to JAVASCRIPT? Code: For i = 0 To num_fields - 1 Forgive me, im still new at this stuff. Thanks. Jay So I am wanting to loop through a set of data an undefined amount of times. For this I need a while loop. However, I want the loop to check for the given condition and continue looping on true, but when it breaks on false - to then execute a different command. Code: while(localStorage.getItem(x) != null) { x++; if(localStorage.getItem(x) == null) { localStorage.setItem(x, account.join(";")); break; } } } This works by continuing to loop everytime with the x++ and the nested if statement inside. The problem gets messier as now I need to perform a separate while loop around the entire thing checking for a different condition. To sum things up, what is the most efficient way to perform a while loop and have one action be performed on success and another if it breaks or reaches a defined condition. I have a dice rolling function. The user enters the number of sides, and the dice rolls 36000 times. I track the results, and then display the percentages of each number being rolled as well. I have it to where it displays but only for ONE die ( eg : a 5 sided die, it only displays up to 5, and not 10 ) But the function is rolling for both die, just not displaying. I'm thinking I need to change, in the rollDice function, <=d.side to <=rolled_value, but whenever I do this, I get NaN errors. Any help would be appreciated! Code: <script type="text/javascript"> function Die(side) { this.side = side; this.roll = function () { var result; result = parseInt(((Math.random() * 1000) % this.side) + 1 ); return result; } // <![CDATA[ this.validateNum = function (side) { if (side > 1 && side < 101) return true; else return false; } } function rollDice() { var d = new Die(document.getElementById('number').value); if (d.validateNum(d.side) == true) { var numCount = new Array(d.side); var percent; var rolled_value; for (var i=1; i<=d.side; i++) numCount[i] = 0; for (var j=0; j<36000; j++) { rolled_value = d.roll() + d.roll(); numCount[rolled_value] = numCount[rolled_value] + 1; } for (var k=1; k <= d.side; k++) document.writeln("Number of" + " " + k +"'s" + " " + "rolled" + ' : ' + numCount[k] + '<br/>' ); for (var l = 1; l <= d.side; l++) { percent = new Number(parseFloat(numCount[l] / 36000) * 100).toFixed(2); document.writeln("Percentage of" + " " + l + " " + "being rolled" + ' : ' + percent + '% <br/>'); } } //]]> Hello, This seems like it should be extremely easy, I think I am missing something fundamental however. First, I have some XML: Code: <aaaaag> <parent text="this is the parent 0"> <child text="zero" /> <child text="one" /> <child text="two" /> <child text="three" /> <child text="four" /> <child text="five" /> </parent> <parent text="this is the parent 1"> <child text="zero" /> <child text="one" /> <child text="two" /> <child text="three" /> <child text="four" /> <child text="five" /> </parent> </aaaaag> And here is a snippet of my js: Code: aaaaag = xmlDoc.getElementsByTagName("aaaaag"); var x = aaaaag[0].childNodes[1].childNodes; cCompA.innerHTML = aaaaag[0].childNodes[1].attributes.getNamedItem("text").nodeValue; // I would have expected childNodes[0] instead !! for (i=1;i<x.length;i+=2) // I would have expected: (i=0;i<x.length;i++) instead !! { cCompB.innerHTML = x[i].attributes.getNamedItem("text").nodeValue + "<br />"; } I really have two questions here, but the first may answer the second. Also it may be worth mentioning I am just trying to work with the "parent 0" for the moment. First, I seem to have hidden nodes in my XML. When accessing the first child as an object, the index is 1, the second is 3 (I have tested this by manually putting in 1,3,5,7,9 etc as the indexs) and so on, rather than starting at 0. I'm not seeing where the hidden nodes are though, and I've run my xml through a validator on W3Cschools.com. I've seen someone recommend not using attributes and instead using a <text>one</text> format, but I am really hoping this isn't the problem as my xml file is fairly long, and it would take quite a bit of effort to rewrite it. The second question is, my for loop only outputs the last child, rather than all the previous children. If anything, I would really expect the last one NOT to get output, because of the i+=2 I am having to do because of the hidden children problem. I'm guessing this is somehow related to the first problem though. Thanks in advance! 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 I have a simple issue that I cannot fix. The code bellow, is a while-loop with RGB color. It displays the word Hello 10 times id 10 different colors. The problem is I cannot get the correct colors displayed. I want the first Hello to be red and end up green in the last one. For some reason I cannot get the color combination correct, even after I put 255 for red and 192 for green. Can you please have a look and tell me what am I doing wrong? Thanks in advance 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>Project 4 - Exercise 10</title> </head> <body> <script language="JavaScript"> var r = 254; var g = 254; var b = 125; for (i=1; i <= 10; i++) { document.write ("<font size=7 color = rgb(" + i + "," + g + ", "+b+")> Hello <br>"); } </script> </body> </html> Function findsometing() ( var myString = 'results' + '<BR>' for (var initiator, test condition,incrementor.) { if (.....) { myString ='some quote'; } else if (.....) { myString += something + '<br>' } else if (....... ) { myString += something + '<br>' } else { myString += ''; } } displayMessage(myString) ) I am a complete newbie to javascript and programming, so excuse any faux pas, but I want to check the myString variable after all the loops in the for loop statement have been completed. For example if nothing was added to the var myString after the completeion of the for loop, i want to display a message that no results found. i tried various attempts of an if statement along lines of } } if (myString = 'results') ....i also tried if myString= ('results' + '<BR>') { displayMessage('no results found') } else { displayMessage(myString) } ) Any pointers as to where i am going wrong? Hello, In the below script syntax, a simple table converts Celsius degrees into Fahrenheit, using the For loop and integrating it into a table. Code: <html> <head> <title>Celsius-Fahrenheit Converter</title> </head> <body> <table border=3> <tr><td>CELSIUS</td><td>FAHRENHEIT</td></tr> <script language="javascript"> for (celsius=0; celsius<=50; celsius=celsius+1) { document.write("<tr><td>"+celsius+"</td><td>"+((celsius*9/5)+32)+"</td></tr>"); } </script> </table> </body> </html> My questions are about the following script inside the <td> tags: <td>"+celsius+"</td> <td>"+((celsius*9/5)+32)+"</td> 1) why is the script inside the above <td> tags placed between " " ? 2) why is the script inside the above <td> tags placed between + + ? Thanks a lot for your explanation to an absolute Javascript beginner...! 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> 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, 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. 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; 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... 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. 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 }?> 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 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 |