JavaScript - Foreach Javascript
I am trying to iterate through a collection of objects...
Code: <!DOCTYPE html> <html> <head> <title>demo</title> <meta charset=utf-8"/> <style type="text/css"> .one{background: blue; width:100px; height:100px; float:left; display:none;} .two{background: orange; width:100px; height:100px; float:left; display:none;} .cOne{display:none; border: 2px solid black; float:left; background: purple; width:50px; height:50px;} </style> <script type="text/javascript"> function hideDiv(selectorOne, selectorTwo){ document.getElementById(selectorOne).style.display = 'block'; document.getElementById(selectorTwo).style.display = 'none'; var elements = document.getElementsByClassName('cOne'); alert(elements); elements.forEach.... } </script> </head> <body> <div id="dOne" class="one">div 1</div> <div id="dTwo" class="two">div 2</div> <hr style="clear:both;"/> <input type="radio" name="options" value="one" onclick="hideDiv('dOne', 'dTwo');">one<br/> <input type="radio" name="options" value="two" onclick="hideDiv('dTwo', 'dOne');">two<br/> <div class="cOne"></div> <div class="cOne"></div> <div class="cOne"></div> <div class="cOne"></div> </body> </html> I assemble the array here... Code: var elements = document.getElementsByClassName('cOne'); and presumably that collection is valid since my alert() shows an "html collection"... I am trying to figure out how to iterate through each one something like the following pseudo-code Code: var elements = doc.getElemByClass('cOne'); foreach(Element elm in elements){ elm.style.display = 'block'; } But I am having trouble finding examples online. I feel like this is along the lines of what I need, but the syntax is eluding me. Similar TutorialsHello Firstly, this is the full pastebin code of my admin page because i failed adding full code here correctly: http://pastebin.com/tQAaQjYC and the screenshot of the slide manager page: http://img36.imageshack.us/img36/4830/slidemanager.jpg Well, I have a Slide Manager as an admin menu page in Wordpress. When i click "Add new slide" button, as you see in the screenshot above, it adds a new "slide field" in which that dropdown list shows all titles of posts. (Ignore other parts as they work as expected) What i would like to do is, when i choose a post title, the text box which is next to dropdown to be populated automatically by the post's url adress. I want it to be worked for every "slide field" added via "Add new slide" button. I actually made it work that way outside the foreach: PHP Code: <script language="JavaScript"><!-- function onChange() { var Current = document.myform.link.selectedIndex; document.myform.currentText3.value = document.myform.link.options[Current].value; } //--> </script> <select name="link" onChange="onChange(this.value);"> <?php if($_POST['action'] == save ) { $selected = "selected"; } else{ $selected = ""; } echo '<option value="">...... Choose One ...... </option>'; $args = array( 'post_type' => 'post', 'nopaging' => true ); $the_query = new WP_Query( $args ); while ( $the_query->have_posts() ) : $the_query->the_post(); echo '<option '.$selected.' value="'.get_permalink( $post->ID ).'">'; the_title(); echo '</option>'; endwhile; ?> </select> <input name="currentText3" type="text" value=""> But when i add this after the opening code of foreach, i.e: PHP Code: <?php foreach($nivoslides as $k => $slide) : ?> Each slide field shows the dropdown and text box properly as you see in screenshot BUT none of them work. I tried to add brackets but it didn't work either: Code: <select name="link[]" onChange="onChange(this.value);"> I guess it's the javascript code that should be edited or entirely changed but i have no idea how to do it. I would be grateful for any help. Thanks in advance. Hello folks: I've got an html table populated by a php foreach routine. One field in this table is an Input type=checkbox. The goal is to run a javascript function when the user checks the checkbox. But, since the checkbox is in a table populated by a foreach routine, I'm having some problems. Below is the applicable code for my table: <?php foreach($results as $row) { $bk_owner = $row['BookOwner']; $addrss_owner = $row['AddressOwner']; $f_name = $row['FName']; $l_name = $row['LName']; $email = $row['EmailAddress']; $d_phone = $row['DeskPhone']; $ext = $row['Ext']; $cell = $row['CellPhone']; $title = $row['Title']; echo "<tr>"; echo "<td class='a'>".$l_name ."</td>"; echo "<td class ='a'>".$f_name ."</td>"; echo "<td class ='c'>".$email ."</td>"; echo "<td class ='a'>".$d_phone ."</td>"; echo "<td class='b'>".$ext."</td>"; echo "<td class='a'>".$cell."</td>"; echo "<td class='c'>".$title."</td>"; echo "<td class='b'><input type='checkbox' id='chk_Bx' value=". $addrss_owner. " onClick='selectFunction()'></input></td>"; echo "</tr>"; } echo"</tbody>"; ?> Specifically, note this line: echo "<td class='b'><input type='checkbox' id='chk_Bx' value=". $addrss_owner. " onClick='selectFunction()'></input></td>"; the value is set to $address_owner. This value is a primary key value and will allow me to run routines related to the record chosen when the checkbox is checked. Following is the javascript code for selectFunction(): function selectFunction(){ var check = document.getElementById("chk_Bx").checked; var val = document.getElementById("chk_Bx").value; alert(val); } At this point the javascript is very simple. All I'm trying to do is pick up applicable values for the record selected. But - I believe because the table is populated through a foreach loop, the javascript alert is returning the same primary key value for every record checked (or unchecked). Also, if I alert out check, it continually returns false, even if I've checked the box and it should read true. I am assuming this is also related to the foreach table presentation. How do I grab ONLY the primary key value, or checked true/false for the applicable record? Thanks in advance: Pavilion Hello! I am trying to find a script that allows you to open multiple browser tabs and then close each of those tabs, either one by one or all at once. Does anyone know how to do this please? Thanks so much for your help. I want to have another go at Javascript. I have several books on the subject but I find that my eyesight is a major problem. Therefore I want to try an on-line solution, preferably free. I have Googled, but there are so many that I am almost dizzy with the choices. Perhaps someone could recommend one. Not too fussy visually. My knowledge is VERY basic. Frank Does anyone know how to make URL links that use Javascript still work when users have Javascript disabled on their browser? The only reason I'm using JS on a URL is because my link opens a PDF file, and I'm forcing it not to cache so users have the latest version. I tried the <script><noscript> tags, but I'm not sure if I'm using it correctly, as my URL completely disappears. Below is my HTML/Javascript code: <p class="download"> <script type="text/javascript">document.write("<span style=\"text-decoration: underline;\"><a href=\"javascript:void(0);\" onclick=\"window.open( 'http://www.webchild.com.au/mediakit/Direct_Media_Kit_Web.pdf?nocache='+ Math.floor( Math.random()*11 ) );\" >The Child Magazines Media Kit</a></span> (PDF 1 MB) ");</script> <noscript><span style="text-decoration: underline;"><a href="http://www.webchild.com.au/mediakit/Direct_Media_Kit_Web.pdf" >The Child Magazines Media Kit</a></span> (PDF 1 MB)</noscript> </p> Thanks for any help, Michael Hi Guys, I am new at JavaScript and start to do some tutorials.What I am trying to do here is prompting user to input a name and if the name was valid the page(document) will display with all objects like the button.But if user enter a wrong name then the button will be disabled! I create the following code but it did not work <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>New Web Project</title> <script language="JavaScript" type=""> function changeColor(){ document.bgColor = "Gray"; } </script> </head> <body> <script language="JavaScript" type="text/javascript"> var person = ""; person = prompt('What is Your Name:'); if (person == "Foo") { document.write("<h1 />Welcome " + person); document.bgColor = "Yellow"; } else { document.write("<h1 />Access Denied!!!!"); document.bgColor = "Red"; document.getElementById("gree").disabled = true; } </script> <div> <p/><input id="gree" type="button" value="Gray " onClick="changeColor();"> </div> </body> </html> as you can see I used the: document.getElementById("gree").disabled = true; but it did not work , could you please give an idea how I can solve this problem? Thanks Hi, I have the following code snippet: test.html ====== <script language="javascript" type="text/javascript"> var testVariable = "test"; </script> <script language="javascript" type="text/javascript" src="test.js"> </script> test.js ===== var testVariable = window.top.testVariable; In firefox, I'm able to access testvariable defined within test.html in test.js. But in chrome, test.js couldnot get the window.top.testVariable field defined in test.html. Can any one please let me know how i can make it work in chrome?. Am i missing something here?. Hey, I've got to make the values of some textboxes change the co-ordinates of my sprite on a canvas and havent a clue on how to do it, Here is my form with the two textboxes and submit button: <form> x: <input type="text" name="x" /><br /> y: <input type="text" name:"y" /><br /> <input type="submit" value="Submit"/><br /> </form> And i need it so that they change the values of these: //this shows where my sprite will start on the canvas var block_x; var block_y; searched the internet for hours and cant really find anything i understand or works. any help is much appreciated I want to insert this js snippet Code: function addText(smiley) { document.getElementById('message').value += " " + smiley + " "; document.getElementById('message').focus(); return false; } to a loaded iframe with name&id chtifrm. I can access it & change embed something in its html via using something like: Code: $(parent.chtifrm.document.body).append('<div id=\"smly\" style=\"cursor:pointer;float:left;top:200px;display:none;position:absolute;\"><\/div>'); .... Code: parent.chtifrm.document.getElementById('chatbox_option_disco').style.display == 'none' but how do I insert js in the head of loaded iframe? I got an index.php Code: <html> <form action="bacakomik.php" method='post'> <select name="kodekomik"> <option value='../komik1/|23'>Judul Komik1</option> <option value="../komik2/|20">Judul Komik2</option> <option value="../komik3/|10">Juduk Komik3</option> <option value="../komik4/|20">Judul Komik4</option> </select> <input type="submit" /> </form> <?php echo ('<select>'); echo ('<option value= "'.$i.'">'.'Page '.$i.'</option>'); echo ('</select>'); ?> </html> As you can see, each of the option brings specific value "../komik1/|23" komik1 is a directory | is a delimiter 23 is the pages in one chapter and can be considered also as how many images are there on a specific directory This is my bacakomik.php Code: <?php $dirkomik = $_POST['kodekomik']; $exploded = explode("|", $dirkomik); echo ($exploded[0]); //picture directory echo ("<br>"); echo ($exploded[1]); //total page in the comic $pagecount = (int)$exploded[1]; //Take last posted value, process it right away echo ('<FORM name="guideform"> '); echo ('<select name="guidelinks">'); $i=1; do { echo ('<option value= "'.$i.'">'.'Page '.$i.'</option>'); $i= $i+1; }while($i <= $pagecount); //Printing option and select echo ("</select>"); ?> <input type="button" name="go" value="Go!" onClick="document.getElementById('im').src=document.guideform.guidelinks.options[document.guideform.guidelinks.selectedIndex].value+'.png';"> </FORM> <img src="img0.jpg" id="im"> With the current code on bacakomik.php, I only can change the img src of id "im" in the same directory only. What I want is that the Javascript could "add" the "$exploded[0]" variable so that the picture can be loaded from different directory. Anyone can do this? I believe that the fix should be somewhere on input tag inside OnClick, or do you know where? Anyway, I found this on the net http://p2p.wrox.com/php-faqs/11606-q...avascript.html Please help me to those who can... Hi Guys I am trying to modify the functionality of my page. I want to be able to activate this piece of code using another javascript function. This is the code I want to activate: Code: <script type="text/javascript"><!-- $('#button-cart').bind('click', function() { $.ajax({ url: 'index.php?route=checkout/cart/update', type: 'post', data: $('.product-info input[type=\'text\'], .product-info input[type=\'hidden\'], .product-info input[type=\'radio\']:checked, .product-info input[type=\'checkbox\']:checked, .product-info select, .product-info textarea, .date_data input[type=\'text\']'), dataType: 'json', success: function(json) { $('.success, .warning, .attention, information, .error').remove(); if (json['error']) { if (json['error']['warning']) { $('#notification').html('<div class="warning" style="display: none;">' + json['error']['warning'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>'); $('.warning').fadeIn('slow'); } for (i in json['error']) { $('#option-' + i).after('<span class="error">' + json['error'][i] + '</span>'); } } if (json['success']) { $('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>'); $('.success').fadeIn('slow'); $('#cart_total').html(json['total']); $('html, body').animate({ scrollTop: 0 }, 'slow'); } } }); }); //--></script> And this is how I want the format of the function to be: function testsession() { if there is a session called 'hiredate' { activate the script above } else { var el = document.getElementById("product_data"); } } I just dont know how to write this in javascript Could you help me if possible please All -- I have a JavaScript config file called gameSetting.js which contains a bunch of variables which configures a particular game. I also have a shared JavaScript library which uses the variables in gameSetting.js, which I include like so: <script type="text/javascript" src="gameSetting.js" ></script> <script type="text/javascript" src="gameLibrary.js" ></script> In gameSetting.js I have: $(document).ready(function() { // call some functions / classes in gameLibrary.js } in Firefox, Safari, and Chrome, this works fine. However, in IE, when it's parsing gameSetting.js, it complains that the functions that live in gameLibrary.js aren't defined. When it gets to parsing gameLibrary.js, the variables in gameSetting.js are reported as not being defined. I've tried dynamically bootstrapping the gameLibrary file using this function in document.ready for dynamic load... $.getScript("gameLibrary.js"); However, the same problem still happens in IE, where when it parses the files individually it's not taking into context the file/variables that came before, so it's not an out of load order problem. My options a 1) collapsing all the functions in gameLibrary.js and variables in gameSetting.js into one file. However, this is not practical because this is dealing with literally hundreds of games, and having a gameLibrary.js in ONE location for ONE update is what makes most logical sense. 2) figure out a way to get this to work where variables in file1 are accessible to file2 in IE (as it seems they are in other browsers). jQuery seems to be able to have multiple plugins that all refer to the based jQuery-1.3.2.js, so I know there is a way to get this to work. Help appreciated. Nero I wrote a log function that took note of various function calls. Thinking that functions are first class objects, and objects have properties, I made the name of each logged function a property of that function, e.g., brightenInnerPara.name = "brightenInnerPara"; Every browser I tried (Firefox, MSIE, Opera, Chrome, Safari) accepted the assignment, no problem. In Firefox and MSIE, the result was what I wanted: brightenInnerPara.name == "brightenInnerPara" But in the others, the result was: brightenInnerPara.name == null Question 1. Which Javascript is correct here? I favor Firefox and MSIE, not merely because they were willing to give me what I wanted, but also because it makes no sense to accept an assignment statement without throwing an error and then give it a null semantics, like Chrome, Opera, and Safari did. I found a workaround, using assignments like this: brightenInnerPara.prototype.name = "brightenInnerPara"; To my surprise, that worked in every browser. But I don't know why. It seems that such assignments are enough to cause each function to have its own distinct prototype. Question 2. Just how inefficient is my workaround, and why does it work? I am running a flash detection script which I will include below... It is called by... Code: <script type="text/javascript"> //<![CDATA[ var requiredFlashVersion = 8; var hasFlashURL = 'http://www.*****.org.uk/'; var upgradeFlashURL = document.location.href + "?flash=ug"; var noFlashURL = 'http://www.*****.org.uk/text_version/**********.html'; var dontKnowFlashVersionURL = document.location.href + "?flash=dk"; //]]> </script> <script type="text/javascript" src="flash_detect.js"> //<![CDATA[ function getFlashVersion() { return null; }; //]]> </script> <script type="text/javascript" src="flash_redirect.js"> //<![CDATA[ location.href = dontKnowFlashVersionURL; //]]> </script> as you can see it determines whether the user has flash and refreshes the page with the according url paramater or sends them on their way. The problem I have is that because it refreshes the page the script runs again and again and just readds the url paramater every time... so it keeps refreshing until the url looks like this: index.html?flash=dk?flash=dk?flash=dk?flash=dk?flash=dk. I want a way to make it realise it has done its job and not run after its first service. Everything I have tried such as using an incremental variable has lead to it loading index.html/undefined (I probably executed this wrong). Here is the external js files for the redirection: flash_detect.js Code: // Flash Version Detector v1.2.1 // documentation: http://www.dithered.com/javascript/flash_detect/index.html // license: http://creativecommons.org/licenses/by/1.0/ // code by Chris Nott (chris[at]dithered[dot]com) // with VBScript code from Alastair Hamilton (now somewhat modified) function isDefined(property) { return (typeof property != 'undefined'); } var flashVersion = 0; var count = 0; function getFlashVersion() { var latestFlashVersion = 8; var agent = navigator.userAgent.toLowerCase(); // NS3 needs flashVersion to be a local variable if (agent.indexOf("mozilla/3") != -1 && agent.indexOf("msie") == -1) { flashVersion = 0; } if (agent.indexOf("firefox") != -1 && agent.indexOf("msie") == -1) { flashVersion = -2; } // NS3+, Opera3+, IE5+ Mac (support plugin array): check for Flash plugin in plugin array if (navigator.plugins != null && navigator.plugins.length > 0) { var flashPlugin = navigator.plugins['Shockwave Flash']; if (typeof flashPlugin == 'object') { for (var i = latestFlashVersion; i >= 3; i--) { if (flashPlugin.description.indexOf(i + '.') != -1) { flashVersion = i; break; } } } } // IE4+ Win32: attempt to create an ActiveX object using VBScript else if (agent.indexOf("msie") != -1 && parseInt(navigator.appVersion) >= 4 && agent.indexOf("win")!=-1 && agent.indexOf("16bit")==-1) { var doc = '<scr' + 'ipt language="VBScript"\> \n'; doc += 'On Error Resume Next \n'; doc += 'Dim obFlash \n'; doc += 'For i = ' + latestFlashVersion + ' To 3 Step -1 \n'; doc += ' Set obFlash = CreateObject("ShockwaveFlash.ShockwaveFlash." & i) \n'; doc += ' If IsObject(obFlash) Then \n'; doc += ' flashVersion = i \n'; doc += ' Exit For \n'; doc += ' End If \n'; doc += 'Next \n'; doc += '</scr' + 'ipt\> \n'; document.write(doc); } // WebTV 2.5 supports flash 3 else if (agent.indexOf("webtv/2.5") != -1) flashVersion = 3; // older WebTV supports flash 2 else if (agent.indexOf("webtv") != -1) flashVersion = 2; // Can't detect in all other cases else { flashVersion = flashVersion_DONTKNOW; } return flashVersion; } flashVersion_DONTKNOW = -1; flash_redirect.js Code: // Flash Detection / Redirect v1.1.1 // documentation: http://www.dithered.com/javascript/flash_redirect/index.html // license: http://creativecommons.org/licenses/by/1.0/ // code by Chris Nott (chris[at]dithered[dot]com) // requires: flash_detect.js (http://www.dithered.com/javascript/flash_detect/index.html) // use flash_detect.js to return the Flash version var flashVersion = getFlashVersion(); // Redirect to appropriate page if (flashVersion >= requiredFlashVersion) location.replace(hasFlashURL); else if (flashVersion > 0) location.replace(upgradeFlashURL); else if (flashVersion == -2) location.replace(dontKnowFlashVersionURL); else if (flashVersion == 0) location.replace(noFlashURL); else if (flashVersion == flashVersion_DONTKNOW || flashVersion == null) location.replace(dontKnowFlashVersionURL); Your help is appreciated but please go into detail as I have a minor understanding of Javascript. Edit: Resolved. Instead of using paramaters I changed the anchor and used jquery to search for the string. I am able to incorporate CSS into the HTML, like this: Code: <tr><td style="background-color:#FFFF00;">test</td></tr> How can I incorporate CSS into javascript? Code: document.writeln("<tr><td style="background-color:#FFFF00;">" + "test" + "</td></tr>"); The javascript code doesn't work or this is it even possible? Thanks I have a little problem, i don't know what the problem is so please help me! What i want the page to do is that you have 2 buttons that you can click. One button you click to get points, when you have 15 points you can upgrade autoclick with 0.1 per second Thank you in Advance ) [/quote][/code] <html> <head> <title>Help/title> </head> <body> <p>Your Points:</p> <p id"Points">0</p> <button onclick="Click()">Click</button> <button onclick="AutoClickBuy()">Buy Auto-Click</button> </body> <script type="text/javascript"> function Click() { var newValue = parseInt(document.getElementByID("Points").innerHTML) +1; document.getElementByID("Points").innerHTML = newValue; } function AutoClickBuy() { var PointsValue = parseInt(document.getElementByID("Points").innerHTML); if (PointsValue > 14) { var newValue = parseInt(document.getElementByID("Points")innerHTML) - 15; document.getElementByID("Points").innerHTML = newValue; var myVar=setInterval(function(){CollectAutoClick()},1000); } } function CollectAutoClick() { var newValue = parseFloat(document.getElementByID("Points").innerHTML) + 0.1; document.getElementByID("Points").innerHTML = newValue; } </script> </html> Reply With Quote 01-26-2015, 06:52 PM #2 Philip M View Profile View Forum Posts Supreme Master coder! Join Date Jun 2002 Location London, England Posts 18,371 Thanks 204 Thanked 2,573 Times in 2,551 Posts Suggest you fix the errors in your markup first. See The W3C Markup Validation Service You have </body> wrongly placed. And an error here - <p id"Points">0</p> And here - <title>Help/title> BTW, when posting here please help us to help you by making it easier to view, copy, modify, test and debug your scripts by following the posting guidelines and wrapping your code in CODE tags. This means use the octothorpe or # button on the toolbar. Do please read the posting guidelines regarding silly thread titles. The thread title is supposed to help people who have a similar problem in future. Yours is useless for this purpose. Everyone here is looking for help with Javascript. Hi all I am having x.php file in that i have included (y.js file). x.php code <? $username = "Kelvin"; ?> y.js code (external file) var username =<?php echo'$username';?> alert(username) It is not working for me. How can i get the php variable in external js file. Any help! Sir my problem is i have checkboxes in row of while loop php, and same row have a column have size of image from database lik "125 x125". so i want to have a script that call on checkbox onlclick event like below code. suppose i click on checkbox it save the size of image in a variable and after that if i check another checkbox then function compare the first size that saved. if size match then no alert but if size not match alert shows "size does not match" Code: <input type="checkbox" name= "checkbox[]" value ="" onclick="required Function"> please sir help me in this matter i am so worry! hi friends, i'm new to javascript, can you please help me on these? what does this means: <B /> what about this : document.writeln("It works!<BR />"); and this: document.writeln('Test'); Thanks |