JavaScript - Arrays Causing Some Confusion.
Hi all,
I am a little stuck trying to use arrays for the purpose of creating a currency converter. I have created the script below but it seem to work fine without the arrays added in. Any ideas? <script type="text/javascript"> function currencyConverter() { //declare and initialise variables var CurrYen = 128.7; var CurrUSDollar = 1.59; var CurrEuro = 1.15; var CurrSwissFrank = 2.06; var CurrDanishKorona = 9.69; var strCurrency = new Array(5); var dblExchange = new Array(5); var dblGross var dblCurrency //collect information from drop-down menu and text boxes strCurrency = document.getElementById("cmbCurrency").value; intSterling = document.getElementById("txtSterling").value //selection if (strCurrency == "Yen") { dblCurrency = CurrYen; } else if (strCurrency == "US Dollar") { dblCurrency = CurrUSDollar; } else if (strCurrency == "Euro") { dblCurrency = CurrEuro; } else if (strCurrency == "Swiss Frank") { dblCurrency = CurrSwissFrank; } else if (strCurrency == "Danish Korona") { dblCurrency = CurrDanishKorona; } else { dblCurrency = 0; } //calculate total currency to convert dblGross = dblCurrency * intSterling; //display total cost document.getElementById("txtSterling").value = dblGross.toFixed(2); } </SCRIPT> Similar TutorialsI need to loop the alphabet and numbers 0-9 to initialize a few thousand arrays. This is for my site and is truly needed. http://www.thefreemenu.com I currently have every array written out and it takes up to much space in my .js file. The majority of my variables are empty but necessary and need to be there (including empty) for my site to work properly. Question is the last part Here's where I'm at. Code: var NewVarLetterOrNum = "a"; eval("_oneofseveralnames_" + NewVarLetterOrNum + "='this part works';"); alert(_oneofseveralnames_a); This creates the variable _oneofseveralnames_a='this part works' Code: var newArrayLetterOrNum = "a"; eval("_oneofseveralnames_" + newArrayLetterOrNum + "= new Array();"); alert(_oneofseveralnames_a) This creates the Array _oneofseveralnames_a=new Array(); and all the values in the array are null, but, now a variable like _nl_a[1]='something' can be used elsewhere because the array exists. This is all that is necessary for now because I can probably set all the variables to be blank with something like Code: i=1 while(i<=20){ _oneofseveralnames_a[i]="1-20"; i++ } alert(_oneofseveralnames_[20]); So now you have what I came to understand in the first few hours. Now to the hard part : ( I can't make multiple array's dynamically. I dont' know if its because I don't understand loops or arrays or what and its very fustrating. As for any answer you might be so kind as to provide, if you could dumb it down that would be greatly appreciated. Code: var newArray =new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z') i=1 while(i<=26){ eval("_nl_" + newArray[i] + "= new Array();"); i++ } alert(newArray[1]) // Is b, but alert(_nl_b) //I can't get _nl_b to exist, I tried everything including taking away the quotes around the letters in every test */ var _nl_a =new Array() var _img_a =new Array() var _h_a =new Array() var _r_a =new Array() var _m_a =new Array() var _yt_a =new Array() var _i_a =new Array() The above arrays are all the array _name_ parts I need but for example, a has 10 parts, a,p2_a,p3_a,.. p10_a. I need 10 pages for each letter of the alphabet and numbers 0-9 and a special all1, p2_all1 ... p10_all1. Overall 2200 arrays that need to be declared. Currently they are all written out. /* Can anyone tell me how the following code actually works please? I've been trying to work out exactly why I need it all, but can't understand it at all! Code: var speed = 50 var myInterval var pause function start(){ window.clearInterval(pause) myInterval = setInterval("auto()",speed) } pause = setInterval("start()",3000) The body onLoad is set to run start(). If anyone can explain why this code is needed I would be very greatful. Hello, I'm working on a set of animation code for school and I keep getting an error like this: Uncaught SyntaxError: Unexpected token ILLEGAL on line 25 of the code. What am I missing and/or what is out of place? Code: var canvas; var context; var CanvasWidth = 0; var CanvasHeight = 0; var FPS = 60; var x = 0; var y = 0; var background; var critter = []; window.onload = init; function init() { canvas = document.getElementById("myCanvas"); context = canvas.getContext("2d"); CanvasWidth = canvas.width; CanvasHeight = canvas.height; background = new Background(); for (var i = 0; i < 6; i++); } { critter[i] = new Critter(); }  function Background () { var obj ={}; obj.draw = function() { context.clearRect(0, 0, CanvasWidth, CanvasHeight); var gradient = context.createLinearGradient(0, 0, 0, CanvasHeight); gradient.addColorStop(0.0, "#C0F5E7"); gradient.addColorStop(0.8, "#3F43E7"); gradient.addColorStop(0.81, "#AF8553"); gradient.addColorStop(1.0, "#E6CBAB"); setInterval(loop, 1000/FPS ); context.fillStyle = gradient; context.fillRect(0, 0, CanvasWidth, CanvasHeight); }; return obj; } function Critter() { var obj = {}; obj.x = 0; obj.y = 0; obj.vx = Math.random() * 2 - 1; obj.vy = Math.random() * 2 - 1; obj.update = function() { obj.x += obj.vx; obj.y += obj.vy; } function bounds() { if (obj.x > canvas.width) { obj.x = Math.random() * 2 - 1; obj.y = Math.random() * 2 - 1; obj.x += obj.vx; obj.y += obj.vy; } } obj.draw = function() { context.fillStyle="#AA0000"; context.fillRect(obj.x, obj.y, 25 , 25); }; } } function draw() { context.clearRect(0, 0, CanvasWidth, CanvasHeight); background.draw(); for (var i = 0; i < critter.length-1; i++) { critter[i].draw(); } } function loop() { update(); draw(); } function update() { for (var i = 0; i < critter.length-1; i++) { critter[i].update(); } critter[i].bounds(); } This is some code that I found that does what I need to do. However in this code I need to create a new var for each item. I have a lot of item in my list that I want to add to the drop down. Is there a simpler way to do this in JS? Cheers Daniel. Code: <HTML> <HEAD> <TITLE></TITLE> <META NAME="GENERATOR" Content="Microsoft Visual Studio"> <META HTTP-EQUIV="Content-Type" content="text/html; charset=UTF-8"> </HEAD> <BODY> <input type="button" value="Show me the menu!" onclick="populateSelect();" ID=Button1/> <input type="button" value="Clear it" onclick="var f = document.getElementById('foodOptions'); while (f.hasChildNodes()) { f.removeChild(f.firstChild); }" ID=Button2/> <script> function populateSelect() { // create optgroups var breakfast = document.createElement("optgroup"); breakfast.label = "Breakfast"; var lunch = document.createElement("optgroup"); lunch.label = "Lunch"; var dinner = document.createElement("optgroup"); dinner.label = "Dinner"; // create options and attach to optgroups var cereal = document.createElement("option"); cereal.value = "cereal"; cereal.appendChild(document.createTextNode("Cereal")); breakfast.appendChild(cereal); var eggs = document.createElement("option"); eggs.value = "eggs"; eggs.appendChild(document.createTextNode("Eggs")); breakfast.appendChild(eggs); var toast = document.createElement("option"); toast.value = "toast"; toast.appendChild(document.createTextNode("Toast")); breakfast.appendChild(toast); var sandwich = document.createElement("option"); sandwich.value = "sandwich"; sandwich.appendChild(document.createTextNode("Sandwich")); lunch.appendChild(sandwich); var soup = document.createElement("option"); soup.value = "soup"; soup.appendChild(document.createTextNode("Soup")); lunch.appendChild(soup); var meat = document.createElement("option"); meat.value = "meat"; meat.appendChild(document.createTextNode("Meat")); dinner.appendChild(meat); var potatoes = document.createElement("option"); potatoes.value = "potatoes"; potatoes.appendChild(document.createTextNode("Potatoes")); dinner.appendChild(potatoes); var vegetables = document.createElement("option"); vegetables.value = "vegetables"; vegetables.appendChild(document.createTextNode("Vegetables")); dinner.appendChild(vegetables); // set "eggs" as the default eggs.selected = true; // clear select menu and append optgroups var selectMenu = document.getElementById("foodOptions"); while (selectMenu.hasChildNodes()) { selectMenu.removeChild(selectMenu.firstChild); } if (breakfast.hasChildNodes()) { selectMenu.appendChild(breakfast); } if (lunch.hasChildNodes()) { selectMenu.appendChild(lunch); } if (dinner.hasChildNodes()) { selectMenu.appendChild(dinner); } } </script> <select id=foodOptions></select> </BODY> </HTML> Can anyone tell me why the string comparison test doesn't work in this javascript function? It works if you use just text between the currentItem div tags, but not when you use html for an image. I even tried to use iso characters instead of angle brackets, as in "<img src=expand.png></img>" and still no dice. Why not? Code: <html> <head></head> <body> <script language="JavaScript"> function toggleValue() { if(document.getElementById("currentItem").innerHTML != "<img src=expand.png></img>") { document.getElementById("currentItem").innerHTML = "<img src=expand.png></img>"; }else { document.getElementById("currentItem").innerHTML = "<img src=collapse.png></img>"; } } //--> </script> <table width =" 200" border="0"> <tr> <td colspan=2><br><center> <a href="javascript:toggleValue()">Toggle Value</a> </center></td> </tr> <tr> <td> <strong>Value:</strong> </td><td> <div id="currentItem"><img src=expand.png></img></div> </td> </tr> </table> </body> </html> Thanks, Neil Why does... Code: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html><head><title></title> <script language = "javascript"> function start() {document.writeln (testPara.innerHTML = "Object reassignment");} </script></head> <body onload="start()"> <p id="testPara">Paragraph</p> </body></html> ... only produce the output "Object reassignment"? After the onload event fires to execute the document.writeln method, isn't <body> processed to output the "testPara" object, now redefined, a 2nd time? Why does it not? What am I missing? Hello I'm having a very simple RegExp problem. I have the text: Code: sddsfdfs[br][CARET][br]<i>[/quote]</i></div> And I want to match it against a Javascript RegExp: \[br\].*?\[\/quote\]<\/i> Note I used to the non-greedy quantifier ( ? ) for .* , such that it should match the minimum. I am expecting it therefore to match the first in the quote below, but instead it is matching the second: Code: 1. [br]<i>[/quote]</i> ------------------------------------------------- 2. [br][CARET][br]<i>[/quote]</i> I'm sure I've just missed something, I'd very grateful if someone could point out what this is? Thanks please pardon my ignorance, but I'm clueless as to why this won't work.... the following is in the header of my page. The first part is the "menu" of the page, the second ( <script type="text/javascript" src="rotate1.js.js"> ) is an external script that rotates an image on the page..... the 2nd works perfectly in a page by itself, but when I insert it in the template with the menu script, images won't rotate. I know I'm missing something that tells the 2nd script to run, but I just don't know what it is? I'm just frustrated with myself that I can't figure it out and i've read so many forums/tutorials/helps that I've only succeeded in confusing myself further! HA! i apologize again for my ignorance... last time i did a web site was 8 years ago, but my boss is paying me to get this done and I REALLY need to pay my phone bill this week!!! Code: <script language="Javascript"> <!-- <!-- function gotoURL(u) { document.location = u; } function turnon(i) { if (document.getElementById || (document.all && !document.GetElementById)) i.style.backgroundColor = "#baccfc"; i.style.textColor } function turnoff(i) { if (document.getElementById || (document.all && !document.GetElementById)) i.style.backgroundColor = "#3462fd"; } <script type="text/javascript" src="rotate1.js.js"> --> //--> </script> Thanks in advance for ANY advice you may have!!!! Alright, so I've been writing a plain javascript file, which is called by HTML later to grab information from a certain page and then parse through that information. This is being done as a Windows Gadget, so the "browser" is IE. I have two main problems with this: One is caching. I can't get not caching to work at all. I've tried headers and I've tried putting something random at the end of the URL. The randomness at the end of the URL works when done from an HTML file embedded with Javascript but will not work from a pure Javascript file. My other, potentially bigger, problem is that the xmlhttp object does not seem to ever want to open again. I'm pretty sure what's happening is it doesn't get back into ready state 4. That is, unless I run an html file that accesses the same url. Then, suddenly, the gadget runs its update function and it actually decides to work. The gadget still runs the update function otherwise but it doesn't actually do anything, which is I believe caused by it never getting back to ready state 4 on its own. I appreciate any help on this, and if I didn't explain anything clearly I'm more than happy to clarify. Cheers. Can someone tel me the code to put a dropdown box showing default values as shown below using script ..i,e by enclosing them in document.write in script <CODE> <SELECT NAME="choice" > <OPTION VALUE="1">one </OPTION > <OPTION VALUE="2">two </OPTION > <OPTION SELECTED VALUE=" 5 "> 5 </OPTION> </SELECT> </CODE> I'm trying to run two javascript files on a web page and there appears to be a conflict. Im using InnerFade with JQuery which can be seen at: http://medienfreunde.com/lab/innerfade/ And Im using Lightbox2 which is at http://www.huddletogether.com/projec...box2/#download If I use them individually they work fine but as soon as I call them together the one won't work. I'm not fluent in javascript so I would really appreciate any help with this. Thanks. hello i am trying to include the following following in my code, but it keeps creating an error. i need to know the correct place to include the function.many thanks Code: CODE ---------------------------------------- <script type="text/javascript"> $(function() { $("#flex1").flexigrid( { url: 'staff.php', dataType: 'json', colModel : [ {display: 'ID', name : 'id_con', width : 40, sortable : true, align: 'left'}, {display: 'Name', name : 'name_con', width : 150, sortable : true, align: 'left'}, {display: 'Email', name : 'email_con', width : 150, sortable : true, align: 'left'}, {display: 'Phone', name : 'phone_con', width : 250, sortable : true, align: 'left'}, {display: 'Mobile', name : 'mobile_con', width : 150, sortable : true, align: 'left'}, {display: 'Fax', name : 'fax_con', width : 150, sortable : true, align: 'left'}, {display: 'Notes', name : 'notes_con', width : 250, sortable : true, align: 'left'} ], buttons : [ {name: 'Edit', bclass: 'edit', onpress : doCommand}, {name: 'Delete', bclass: 'delete', onpress : doCommand}, {separator: true} ], searchitems : [ {display: 'Name', name : 'name_con'}, {display: 'Email', name : 'email_con', isdefault: true}, {display: 'Position', name : 'position'} ], sortname: "name_con", sortorder: "asc", usepager: true, title: "Staff", useRp: true, rp: 10, showTableToggleBtn: false, resizable: false, autowidth: true, autoheight: true, singleSelect: true } ); }); FUNCTION ----------------------------------------------------------- function doCommand(com, grid) { if (com == 'Edit') { $('.trSelected', grid).each(function() { var id_con = $(this).attr('id_con'); id_con = id_con.substring(id_con.lastIndexOf('row')+3); alert("Edit row " + id_con); }); } else if (com == 'Delete') { $('.trSelected', grid).each(function() { var id_con = $(this).attr('id_con'); id_con = id_con.substring(id_con.lastIndexOf('row')+3); alert("Delete row " + id_con); I am building a wordpress theme that utilizes a theme options panel. The theme has a area where someone can enter in their email address, and when they do a Thank You message displays. One of the sections in the theme options panel allows the users to modify that message. Right now the message is formated like this: "Thank you for your interest!<br />As soon as as we are ready we will send you an email with all the details." and the page source shows this: Code: $('#right').html("<div id='submitted'></div>"); $('#submitted').html("Thank you for your interest!<br />As soon as as we are ready we will send you an email with all the details.") .hide() .fadeIn(1000, function() { }); (i bolded the thank you message) now the form functions properly the way it should and the thank you message appears accordingly when someone submits their email. However, if the person modifies the message via the theme options panel and uses "Enter" for a return or line break the code looks like this: Code: $('#right').html("<div id='submitted'></div>"); $('#submitted').html("Thank you for your interest! As soon as as we are ready we will send you an email with all the details.") .hide() .fadeIn(1000, function() { }); and this causes the form not to function properly. The thank you message will not show up. Is there a way to fix the java code so a person can use "Enter" if they choose to? Ive narrowed it down to this one section of the javascript. If you need the entire script I can post it. Any help is greatly appreciated. Thank you for your time. EDIT: Ive actually managed to sort this out. The problem was as simple as the onload in the body tag was overriding the onload script in the header. Combining the two solved the problem. Ive recently been appointed to do some work on my employers website. For now, to hold us over until we can manage a complete re-write, I have been asked to just do a little update to the look and feel. One of the things I have done is use the niftycorners code for rounded divs. I have had no trouble implementing this code over all the site pages, until I got to one page. Our product pages. Ive never seen a code placed directly within the body tag, but this is what has been done here. <BODY onload="pricing_init(); attribute_changed();"> This code loads the dynamic pricing feature. Unfortunately, it also causes the nifty corners code I have placed between the head tags to fail. I dont know if its just the odd placement of the code or the code itself as I am just learning js (using the Javascript and Ajax for dummies book). Is there some way I can alter this so that both the dynamic pricing and nifty corners works? thanks in advance for any suggestions. Hello there, I am using Dynamic Drive's dhtml windowfile and when I had a link for it to call the popup window, it makes my site deliver a 500 server error. Here is the line of code I'm adding: Code: echo '<td><a class="link" href="#" onClick="ajaxwin=dhtmlwindow.open('ajaxbox', 'ajax', 'pages/post.php', 'Composing Mode: Post', 'width=650px,height=400px,left=300px,top=100px,resize=0,scrolling=1'); return false">Compose</a></td>'; It is not a php issue, I plaintext the link and it still did the same thing. hello, The following code is causing firefox to crash: Code: if (!e) { alert("!e"); e = window.event; } alert("before"); var x = e.pageX; alert("after"); By 'crash', I mean it just stops running. It doesn't give me an error message or shut down the browser, it just quits reading the script. I get the alert box "!e" and "before" but I don't get anything for "after". At the line var x = e.pageX; it seems to die. This seems to happen anytime I use e, for example e.clientX, e.screenX, e.type, etc. This doesn't occur in IE. Anyone know what the problem is? I was told by Kunena developers that the issue is that when I insert an image or a video in my forum, it is loading after javascript loads setting the height to "static". Unfortunately they didn't know a fix, so I came here I guess the script is causing the forum articles to overflow the height by exactly the same number of pixels as the image/video. When the page is reloaded, the issue is corrected, but its really annoying for visitors who don't know to reload the page. Not to sound like a big dummy or anything, but I have gone through every file in my template and have found absolutely no "static" scripts, so any help in tracking it down would be greatly appreciated as I am not a javascript guru. I have tried preloading the images, but it had no effect. An example of the overflow issue can be found here https://christian-knowledge.com/inde...id=22&id=25#25 At the moment I have changed the overflow value on that particular section to "auto" to get around it for the time being, but its definitively not a good fix. Thank you for your time and I really appreciate any assistance or advice on how to fix this Hi, I want to make a piece of text fade from black to white while someone puts their mouse over it and change it back to black when they move their mouse away. I did it with the following code, but I'm wondering if anyone would do some (or all) of it a different way. Thanks! Code: //convert RGB values to hexidecimal function RGBtoHex(color) { var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color); var R = parseInt(digits[2]); var G = parseInt(digits[3]); var B = parseInt(digits[4]); Hex = new Array(R, G, B); return Hex; } // Start the text fading function FadeStart(id, FadeTo) { Element = document.getElementById(id); OriginalColor = getComputedStyle(Element, null).color; Start = RGBtoHex(FadeTo); rgb = RGBtoHex(OriginalColor); red = (Start[0] - rgb[0])/16; green = (Start[1] - rgb[1])/16; blue = (Start[2] - rgb[2])/16; BeginFading = true; Fade(); } //Actually do the fading function Fade() { var Complete = (BeginFading == true && rgb[0] != Start[0] && rgb[1] != Start[1] && rgb[2] != Start[2]); if (BeginFading == true && rgb[0] != Start[0] && rgb[1] != Start[1] && rgb[2] != Start[2]) { rgb[0] += red; rgb[1] += green; rgb[2] += blue; var ChangeColor = "rgb(" + Math.round(rgb[0]) + ", " + Math.round(rgb[1]) + ", " + Math.round(rgb[2]) + ")"; Element.style.color = ChangeColor; time = setTimeout("Fade()", 500); } } //Return text to original color function FadeStop() { BeginFading = false; clearTimeout(time); if (Element != null) Element.style.color = OriginalColor; } HI,what is wrong here? I am trying to write code to print a message 5 seconds after document has loaded. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <script> var i; function printMsg(){ document.write("delayed string"); //tried adding to this line: clearTimeout(i); } function timedfunc(){ i=setTimeout(printMsg,5000); } </script> </head> <body onload="timedfunc()"> </body> </html> The message appears ok but the page loading bar in the browser + hourglass wont go away (in firefox). |