JavaScript - Javascript For Loop
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> Similar TutorialsHi 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! 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... 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; 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. 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 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> 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 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 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 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! hi i'd like to ask how can i ask for a function inside a for loop , if i remove the loop the code works fine but i need it for 10 rows . please help , here is the code PHP Code: $content .=' <table cellspacing="2" cellpadding="2" border="0" align="center" > <SCRIPT LANGUAGE="JavaScript" type="text/JavaScript"> function doCalcAndSubmit() { // get both values kolicina1 = document.forms["vlez1"].kolicina.value; cena1 = document.forms["vlez1"].cena.value; // do some calculation vkupno1 = kolicina1 * cena1; // set the value in the right field document.forms["vlez1"].vkupno.value = vkupno1; } </script> <form id="vlez1" name="vlez1" method="POST" action="index_execute.php" > <tr valign="middle"> <td></td> <td align="center"><b> Sifra : </b></td> <td align="center"><b> Kolicina : </b></td> <td align="center"><b> Cena : </b></td> <td align="center"><b> Vkupno : </b></td> </tr> '; for($t=1;$t<11;$t++) { $content .= ' <tr valign="middle"> <td>'.$t.'.</td> <td><input type="text" id="sifra" autocomplete="off" name="sifra['.$t.']" align="middle" onblur="normalField(this);" onfocus="fireKeyListener_sifra(event); highlightField(this,1);" onkeyup="getList_sifra(event);" size="25" value="" /></td> <td><input type="text" id="kolicina" name="kolicina['.$t.']" align="middle" size="25" ></td> <td><input type="text" id="cena" name="cena['.$t.']" align="middle" size="25" onblur="doCalcAndSubmit();"></td> <td><input type="text" id="vkupno" disabled name="vkupno['.$t.']" align="middle" size="25" ></td> <input type="hidden" name="hidden_data" value="'.$data.'"> </tr>'; } $content .= '<tr> <td></td> <td></td> <td align="center"><input type="submit" id="submit2" name="submit2" value="Potvrdi" ></td> </tr> </form> </table> '; I'm trying to make it so when you click a cell in a table it runs a function based on the value within that cell. With the current code, no matter what cell is clicked, the alert box displays the same number, which is the last number in my array. The variable, princ, is just being overwritten rather than writing code to each the cell with the proper value. Help is appreciated. Thanks. Code: for(i=0;i<=3;i++){ document.writeln('<tr>'); document.writeln('<th>'+(periodArray[i])+'</th>'); for(j=0;j<=2;j++){ princ = principleArray[j][i]; document.writeln('<td onclick="(calculateInterest(princ,1,1))">$'+principleArray[j][i]+'</td>'); } document.writeln('</tr>'); } function calculateInterest(principle,rate,period){ totalInterest = principle * rate * period; totalLoanCost = principle + totalInterest; alert('Total Interest: '+totalInterest+'\n'+'Total Loan Cost: '+totalLoanCost); } Hi Guys, I have a PHP loop region, which repeats all completed projects for each customer, then displays all jobsheets linked to those projects. I have a javascript show/hide function, which will only show the jobsheets when the project link is clicked. Without this javascript, the PHP loop works perfectly, but all the information is displayed. How can I use the show/hide function and still show all the jobsheets for completed projects? Code: function toggle2(id, link) { var e = document.getElementById(id); if (e.style.display == '') { e.style.display = 'none'; link.innerHTML = '<img src="../Images/plus.gif" border="0" >'; } else { e.style.display = ''; link.innerHTML = '<img src="../Images/minus.gif" border="0" >'; } } PHP Code: <table> <tr> <th>Project / Job</th> <th>Language</th> <th>Words (Net)</th> <th>Shipped</th> </tr> <?php $previousProject = ''; if ($totalRows_rsComplete_Cust > 0) { // Show if recordset not empty while ($row_rsComplete_Cust = mysql_fetch_assoc($rsComplete_Cust)) { if ($previousProject != $row_rsComplete_Cust['projid']) { // for every user, show the user name ?> <tr> <td colspan="4"><a href="#" onclick="toggle2('<?php echo $row_rsComplete_Cust['projid']; ?>', this)"><img src="../Images/plus.gif" border="0" /></a><?php echo $row_rsComplete_Cust['projid']; ?></td> </tr> <?php $previousProject = $row_rsComplete_Cust['projid']; } ?> <tr id="<?php echo $row_rsComplete_Cust['projid']; ?>" style="display:none"> <td><a href="jobsheet_details.php?id=<?php echo $row_rsComplete_Cust['jobid']; ?>&proj=<?php echo $row_rsComplete_Cust['projid']; ?>"><?php echo $row_rsComplete_Cust['jobname']; ?></a></td> <td>LANGUAGE</td> <td>WORD NET</td> <td>YES / NO</td> </tr> <?php }} // Show if recordset not empty ?> </table> Ok javascript gurus, could someone help me out with a simple script? I have an array that I want to loop through and display the values of the array on the page as it loops (so I guess there should be a slight delay before the next one appears over it). I want to loop though until a button is clicked. Help? Hi There, Below is some very basic html/javascript that asks for a user to enter a number in an input text box and then a button is pressed it writes out a line that number of times. It works, but when run in firefox the pages always seems to continue to load... that is, the cursor is continuously that when a page is loading (an arrow with a little circle) and the status bar in the bottom right hand corner seems to be always be at zero. It seems to be something in the for loop as when this is take out it works. Seems to work in IE however? Any ideas? Is this a FireFox thing or am I not terminating the loop properly? Code: <html> <head> <script type="text/javascript" language="javascript"> <!-- function writeloop(){ var noTimes = document.theForm.theAmount.value; for(x=0;x<=noTimes;x++){ document.write("A line!"+"<br />"); } } function cleantext(){ document.theForm.theAmount.value=""; } //--> </script> <title>Write Loop</title> </head> <body> <form name="theForm" action="#"> <input type=button value="Press me" onclick="writeloop();" /> <br /><br /> Enter the amount of times:  <input type=text name="theAmount" value="blah" onfocus="cleantext()"/> </form> </body> Many thanks! Below is the code. My function: Code: function swap_content(id1,id2) { var tmp = document.getElementById(id1).name; var theval = document.getElementsByName('primary_propertyp_id')[0].value; document.getElementById(id1).name = document.getElementsByName('primary_propertyp_id')[0].name; document.getElementsByName('primary_propertyp_id')[0].name = tmp; document.getElementById(id2).id = document.getElementById('primary').id; document.getElementById('primary').id = 'addressid_'+theval+'_div'; } Applicable Code for primary info: Code: <div id="primary"> <label>primary to secondary:</label><input name="primary_propertyp_id" type="text" id="addressid_<? echo $row['primary_property_id']; ?>" value="<? echo $row['primary_property_id']; ?>"/> </div> Applicable Code for secondary info/link to change: Code: echo "<div id=\"addressid_" . $properties_row['id'] . "_div\">"; echo "<a href=\"#\" onclick=\"swap_content('addressid_" . $properties_row['id'] . "','addressid_" . $properties_row['id'] . "_div'); return false\">Make Primary</a>"; echo "<input id=\"addressid_" . $properties_row['id'] . "\" name=\"addressids[]\" value=\"" . $properties_row['id'] . "\" type=\"text\">"; echo "</div>"; This is running through a PHP loop so it's making multiple divs and links for the secondaries. I am wanting to be able to swap out any of them to make them 'primary'....this works for the first click, but after the first click it makes every div id and input name the same as the first that was clicked. It's also not working AT all if i click on the bottom link first, then a link above it. Top-down works, bottom-up doesn't...Please help Thanks in advance, Jeremy |