JavaScript - For-loop Breaks Code. Why?
I have the following code:
Code: <script> $(function() { var inputArr = new Array("#register_id #username_id", "#register_id #email_id", "#register_id #password1_id", "#register_id #password2_id", "#signin_id #email_id", "#signin_id #password_id"); var inputToOverlayDict = new Array(); inputToOverlayDict[inputArr[0]] = "#register_id #usernameOverlay_id"; inputToOverlayDict[inputArr[1]] = "#register_id #emailOverlay_id"; inputToOverlayDict[inputArr[2]] = "#register_id #passwordOverlay1_id"; inputToOverlayDict[inputArr[3]] = "#register_id #passwordOverlay2_id"; inputToOverlayDict[inputArr[4]] = "#signin_id #emailOverlay_id"; inputToOverlayDict[inputArr[5]] = "#signin_id #passwordOverlay_id"; var i; for(i=0; i<6; i++) { $(inputArr[i]).focus(function() { $(inputToOverlayDict[inputArr[i]]).hide(); }); } /* $(inputArr[0]).focus(function() { $(inputToOverlayDict[inputArr[0]]).hide(); }); $(inputArr[0]).blur(function() { if($(this).val().length == 0) $(inputToOverlayDict[inputArr[0]]).show(); }); $(inputArr[1]).focus(function() { $(inputToOverlayDict[inputArr[1]]).hide(); }); $(inputArr[2]).focus(function() { $(inputToOverlayDict[inputArr[2]]).hide(); }); $(inputArr[3]).focus(function() { $(inputToOverlayDict[inputArr[3]]).hide(); }); $(inputArr[4]).focus(function() { $(inputToOverlayDict[inputArr[4]]).hide(); }); $(inputArr[5]).focus(function() { $(inputToOverlayDict[inputArr[5]]).hide(); }); */ }); </script> The whole idea is that if a certain div object comes to focus, something else disappears (using JQuery). For some reason the code in the comments is working fine, but the for loop breaks everything down. Why? Similar Tutorialshi, I have some HTML to edit in my database, in my back end administration I have it in a textarea but when I go to edit it, it all messes up and lots of '/' area added, see below: Code: Site Design by: <a href=\\\\\\\"http://www.jbiddulph.com\\\\\\\" target=\\\\\\\"_blank\\\\\\\" title=\\\\\\\"John Biddulph - Web Development\\\\\\\">jbiddulph.com</a> php code Code: <p> <label>Site Design by</label> <textarea class="text-input small-input" name="SiteDesignby"><?php echo $row1['SiteDesignby'] ?></textarea> </p> Can anyone help please? Hi, I have my page here. There is a tab system on the page that uses javascript. View the source the see the javascript file (tabber9.compressed.js). Now, on my end, I am adding some tracking code. The code looks like this: Code: <SCRIPT TYPE='text/javascript' LANGUAGE='JavaScript'><!-- // window.onload = initPage; function initPage() { if (this.GetCustomerGUID) document.forms["Test"].elements["CustomerGUID"].value = GetCustomerGUID(); } //--></SCRIPT> The problem is, when I add this code to my footer, it breaks the tab system. The tabs don't work any more. I am not a JavaScript expert by any means (or else I would have known what the issue is! lol) but, I guess it has something to do with the window.onload function? I say that because I see the window.onload code in the tabber javascript as well. Any advice or help anyone can give would be greatly appreciated. Thanks in advance for any help! Thanks for looking! I have a widget that lives on a blank/fresh Blogger.com account, and with test pictures, it seems to work fine. However, when I throw in Amazon ads it breaks. Images with links as sample data, rotate and display fine. Changing them to amazon code, they break. What's going on? Am I missing an escape character? Code: <script language="Javascript" type="text/JavaScript"> var ad = new Array() ad[0]=' <iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&bc1=000000&IS2=1&bg1=FFFFFF&fc1=000000&lc1=0000FF&t=netbooknewsco-20&o=1&p=8&l=as4&m=amazon&f=ifr&ref=ss_til&asins=B0051VVOB2" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe> ' ad[1]='<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&bc1=000000&IS2=1&bg1=FFFFFF&fc1=000000&lc1=0000FF&t=netbooknewsco-20&o=1&p=8&l=as4&m=amazon&f=ifr&ref=ss_til&asins=B0051VVOB2" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe> ' function randomorder(targetarray, spacing){ var randomorder=new Array() var the_one var z=0 for (i=0;i<targetarray.length;i++) randomorder[i]=i while (z<targetarray.length){ the_one=Math.floor(Math.random()*targetarray.length) if (targetarray[the_one]!="_selected!"){ document.write(targetarray[the_one]+spacing) targetarray[the_one]="_selected!" z++ } } } </script> <script language="Javascript" type="text/javascript" ></script> <script> randomorder(ad, ' ') </script> resolved
Beginner JavaScripter here. I'm wanting to run a piece of code (add rows) a specified amount of times based upon the number selected. Also, rows can be added after initial number has been specified. Example: User1 selects 2 -> 2 rows are added User1 goes back and selects 3 -> 1 row is added, making 3 rows total I've tried the following, but it seems to not take into account the number of rows already added. Any help is appreciated. Code: if (numSelected > 0) { var counter = 0; while (rowsAdded < numSelected ) { function.addRow(); counter++; } } hi, i want to write a js function which will change images (i have an array of images) on mouse over till the time i have my mouse over the image. i have written function: Code: function changeImage(testImage,source) { var my_array=testImage.split("||"); var actualLen = my_array.length - 2; for (i=0;i<my_array.length;i++) { document.getElementById("lrgPic" + source).setAttribute("src",my_array[i]); setTimeout('',1000); if(i == ( my_array.length - 1 )) { // i = (( my_array.length - 1 ) - i) - 1; // alert(i); } } } but the action i want is: on hovering over the image (location: "lrgPic" in above code) images should keep on changing grabbing the location from array ("my_array" above) and the image change should happen after every sec. i have tried "setTimeout" function; but it's not working as desired. with the code which is commented above.. i want to reset the loop so that images are continuously changed till "onmouseOut" is performed... any clues guys.. how can i improve on this code? with this code.. my script goes in infinite loop.. please help thanks in advance 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. I am trying to get a site working that some hack developed. Got it nearly operational, except for one page, the down arrows do not work. They fire via javascript. It is just a hover and scroll deal. The java gets loaded the same for every page, but it breaks on this one. I am decent with some coding, but I know I am light years behind the smart people in this forum, especially when it comes to java. I really could use a hand. Thanks Working scroll: http://66.147.244.241/~finalco1/inde...mation-fm.html The broken scroller: http://66.147.244.241/~finalco1/inde...act-us-fm.html My page is he http://acq.matthewboehler.com/ I have jQuery script written on my page to create a fade-effect when an image is hovered. See the large, kitchen image in the middle of the screen to see this effect in action. This is done on images with the "fade" class and styled with the second image as its background image. My problem is when I apply the "fade" class to another image, the background image does not appear on a rollover. See the bottom left corner image, when you rollover it goes away. Can someone explain why? Hi, I'm creating a new email in javascript via outlook. When i try entering a line break "\n", "\r", "\r\r", etc, Outlook just ignores it completely. I've tried using "%0D%0A" and "fromCharCode(10)" as well but it doesnt seem to read it as a line break. Is there any way to code it so that a line break or a carriage return appears on outlook? I pulled together a custom RSS twitter feed that uses javascript; however, when I tell the code to "callback" 3 posts, they all run together without line breaks. What is the best way to have breaks between the posts? This page shows the html code (in the right sidebar): http://www.westbrockdesign.com/twitter.html The javascript looks like this: Code: function twitterCallback2(C){var A=[];for(var D=0;D<C.length;D++){var E=C[D].user.screen_name;var B=C[D].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g,function(F){return'<a href="'+F+'">'+F+"</a>"}).replace(/\B@([_a-z0-9]+)/ig,function(F){return F.charAt(0)+'<a href="http://www.twitter.com/'+F.substring(1)+'">'+F.substring(1)+"</a>"});A.push("<span>"+B+'</span> <a style="font-size:85%" href="http://twitter.com/'+E+"/statuses/"+C[D].id+'">'+relative_time(C[D].created_at)+"</a>")}document.getElementById("twitter_gretchen").innerHTML=A.join("")}function relative_time(C){var B=C.split(" ");C=B[1]+" "+B[2]+", "+B[5]+" "+B[3];var A=Date.parse(C);var D=(arguments.length>1)?arguments[1]:new Date();var E=parseInt((D.getTime()-A)/1000);E=E+(D.getTimezoneOffset()*60);if(E<60){return"less than a minute ago"}else{if(E<120){return"about a minute ago"}else{if(E<(60*60)){return(parseInt(E/60)).toString()+" minutes ago"}else{if(E<(120*60)){return"about an hour ago"}else{if(E<(24*60*60)){return"about "+(parseInt(E/3600)).toString()+" hours ago"}else{if(E<(48*60*60)){return"1 day ago"}else{return(parseInt(E/86400)).toString()+" days ago"}}}}}}}; Any insights would be much appreciated! I have the below JS code to change up a select box based on what is selected in another select box. IE9 broke this somehow. It still works in other browsers as well as IE8 and IE7. When you select something in select box A, it properly populates select box B. However when you go back and change select box A again the script stops working completely. The error I'm getting from the IE9 developer tools debugger is: SCRIPT65535: Invalid calling object dynamicselect.js, line 31 character 18 I have bolded the relevant line below. Code: function dynamicSelect(id1, id2) { // Browser and feature tests to see if there is enough W3C DOM support var agt = navigator.userAgent.toLowerCase(); var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1)); var is_mac = (agt.indexOf("mac") != -1); if (!(is_ie && is_mac) && document.getElementById && document.getElementsByTagName) { // Obtain references to both select boxes var sel1 = document.getElementById(id1); var sel2 = document.getElementById(id2); // Clone the dynamic select box var clone = sel2.cloneNode(true); // Obtain references to all cloned options var clonedOptions = clone.getElementsByTagName("option"); // Onload init: call a generic function to display the related options in the dynamic select box refreshDynamicSelectOptions(sel1, sel2, clonedOptions); // Onchange of the main select box: call a generic function to display the related options in the dynamic select box sel1.onchange = function() { refreshDynamicSelectOptions(sel1, sel2, clonedOptions); }; } } function refreshDynamicSelectOptions(sel1, sel2, clonedOptions) { // Delete all options of the dynamic select box while (sel2.options.length) { sel2.remove(0); } // Create regular expression objects for "select" and the value of the selected option of the main select box as class names var pattern1 = /( |^)(select)( |$)/; var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)"); // Iterate through all cloned options for (var i = 0; i < clonedOptions.length; i++) { // If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box if (clonedOptions[i].className.match(pattern1) || clonedOptions[i].className.match(pattern2)) { // Clone the option from the hidden option pool and append it to the dynamic select box sel2.appendChild(clonedOptions[i].cloneNode(true)); } } } Thank you in advance for any help provided. here is my code Code: <ul id="myList" class="myList"> <form method="post" action="somepage"> <li id="item_1"> <a href="#"><img src="images/build/handle.jpg" alt="handle" border="0" /></a> Link Group </li> <li id="item_2"> <a href="#"><img src="images/build/handle.jpg" alt="handle" border="0" /></a> Page Group </li> <li id="item_3"> <a href="#"><img src="images/build/handle.jpg" alt="handle" border="0" /></a> SEO </li> <li id="item_4"> <a href="#"><img src="images/build/handle.jpg" alt="handle" border="0" /></a> <script type="text/javascript"> tinyMCE.init({ mode : "textareas", theme : "advanced" }); function toggleEditor(id) { if (!tinyMCE.get(id)) tinyMCE.execCommand('mceAddControl', false, id); else tinyMCE.execCommand('mceRemoveControl', false, id); } </script> <textarea name="content" style="width:96%"> </textarea> <a href="javascript:toggleEditor('content');">Add/Remove editor</a> </li> </form> </ul> <p id="myList_serialize"></p> <script type="text/javascript" language="javascript" charset="utf-8"> Sortable.create('myList',{ghosting:false,constraint:true,hoverclass:'over', onChange:function(element){ var totElement = 7; var newOrder = Sortable.serialize(element.parentNode); for(i=1; i<=totElement; i++){ newOrder = newOrder.replace("myList[]=",""); newOrder = newOrder.replace("&",","); } $('myList_serialize').innerHTML = '<strong>New Order</strong>: '+newOrder; } }); </script> I some draggable li's which works fine, I have a tinyMCE WYSIWYG editor which works fine! How can I add a form to my UL LI? This is about http://www.aecp.pt You will see this on the page, and I highlight the problem on the screenshot itself: http://skitch.com/ricardosalta/nk9g4...ub-de-portugal I know by trial and error that the problem is caused by the presence of image galleries like this on the homepage: http://skitch.com/ricardosalta/nk988...ub-de-portugal I use Mac; is there a good tool to find these incompatibilities? Anyway, I appreciate all the help you can gift me with. Any pointers will be much valuable. Thanks. All the best, Tatonka I must have spent around 8 hours looking for the JavaScript code I need for putting text on the screen using onclick. Here is the code I found: http://javascript.internet.com/snipp...functions.html Code: /* This script and many more are available free online at The JavaScript Source!! http://javascript.internet.com Created by: HunBug | http://www.astral-consultancy.co.uk/cgi-bin/hunbug/doco.cgi?11430 */ function appendText(node,txt) { node.appendChild(document.createTextNode(txt)); } function appendElement(node,tag,id,htm) { var ne = document.createElement(tag); if(id) ne.id = id; if(htm) ne.innerHTML = htm; node.appendChild(ne); } That works great, but I need to add three lines of text at a time, not just one. I spent at least 4 more hours searching for ways to add a line break with JavaScript, but nothing I have found works with this code. Here's what the onclick code looks like: Code: onclick="appendText(document.getElementById('bb1'),'8,4,6' + '0,0,0' + '16'); <div id="bb1"></div> The page I'm working on will have clickable text and image maps and when you click, three lines of batari Basic code will be added to a DIV. Here's an example of what that code will look like: Code: 8,4,6 0,0,0 16 Click on another link and you'd see something like this: Code: 8,4,6 0,0,0 16 8,12,17 0,0,0 16 It would keep adding three lines of batari Basic code to the list every time you clicked. If somebody can figure out how to stick line breaks in this code that really work, I'll be all set. I have tried <BR>, \n, \r\n and a couple of other things, but nothing works so far. Thanks. Hi I currently have this: var d = new Date() var theDay = d.getDay() switch (theDay) { case 1: document.write("On Air Tonight...") <br> document.write("ALAN POWELL!") document.write("8pm - 10pm") document.write("CARL KANE!") break case 2: document.write("On Air Tonight...") document.write("ALAN POWELL!") document.write("8pm - 10pm") document.write("CARL KANE!") break case 3: document.write("On Air Tonight...") document.write("ALAN POWELL!") document.write("8pm - 10pm") document.write("CARL KANE!") break case 4: document.write("On Air Tonight...") document.write("ALAN POWELL!") document.write("8pm - 10pm") document.write("CARL KANE!") break case 5: document.write("On Air Tonight...") document.write("ALAN POWELL!") document.write("8pm - 10pm") document.write("CARL KANE!") break case 6: document.write("On Air Tonight...") document.write("ALAN POWELL!") document.write("8pm - 10pm") document.write("CARL KANE!") break case 7: document.write("On Air Tonight...") document.write("ALAN POWELL!") document.write("8pm - 10pm") document.write("CARL KANE!") break default: document.write("On Air Tonight...") document.write("ALAN POWELL!") document.write("8pm - 10pm") document.write("CARL KANE!") } Which obviously outputs the following: On Air Tonight...ALAN POWELL!8pm - 10pmCARL KANE! How do i code it so it displays On Air Tonight... ALAN POWELL! 8pm - 10pm CARL KANE! Also in Firefox, its not displaying ANYTHING... is there anything wrong in the code which FF would throw out? CSS validation says everything is ok any help would be fantastic. Thanks in advance UKD. i am dynamically making pdf files, works great using abcpdf etc etc. the only problem that i am having is with the page breaking. i want to create a function that runs onload and can read the position of elements and add breaks before the element if it is cut off. each block ("from the west", "holiday inn express") is a span with the class name of "entry" i want to loop through those, get their height, add them together and if that span falls in the range of the page size (792px) add a page break before it. the difficult part will be when we get to pages 2 and above does that make sense? im throwing around some ideas now in a js file, if you have any please post them thanks |