JavaScript - Using Variable Variables
Hi,
I haven't used variable variables before and I'm still trying to get my head around it. I think I'm going OK but I have run into a fairly obscure little problem that I thought I'd throw out there to see if anyone has any ideas... The plan: to make a distance calculator that measures a line made by clicking on a google map. Overall distance is shown at the side, but segment length is shown in tooltip-like labels called Elabels. Segments can get dragged and segment length is updated as dragging occurs. Being that the number of segments (and labels) depends on the number of user clicks, I thought it would be a good idea to use the variable variable to keep all the references unique. If there's a better way to do this, I'd love to hear about it. The problem: it all works fine, except that, if you consider that dragging a point on a line changes two line lengths (let's say A is the start, B is the drag point and C is the end), only one length is updating - the A to B section. What I want is for the Elabel at C to reflect the change in the B to C line length as well. Anyway. Here's the page I'm working on. The relevant code is below. I've tried duplicating it and adding +1 to the variables (and every permutation thereof) but no dice. All I need really is for exactly what's happening now to be happening in the next Elabel along in the array. Any suggestions much appreciated. Code: function leftClick(overlay, point) { count++; var mar1= count-2; var mar2= count-1; var mar3= count; var mar4= count+1; window["label" + mar2]=new ELabel(point, dist ,"labelstyle",new GSize(10,10)); labels2.push(window["label" + mar2]); map.addOverlay(window["label" + mar2]); // Drag listener GEvent.addListener(marker, "drag", function() { drawOverlay(); window["marker" + mar2]=markers[mar1]; window["marker" + mar3]=markers[mar2]; window["marker" + mar4]=markers[mar3]; line = [window["marker" + mar2].getPoint(),window["marker" + mar3].getPoint()]; dist2=window["marker" + mar2].getPoint().distanceFrom(window["marker" + mar3].getPoint()); dist2="Segment<br> length:<br>"+dist2.toFixed(0)+"m"; if(parseInt(dist2)>10000){dist2=(parseInt(dist2)/1000).toFixed(1)+"km";} window["label" + mar2].setPoint(marker.getPoint()); window["label" + mar2].setContents(dist2); } Similar TutorialsHi, in PHP I can assign a variable do... PHP Code: function setvar($anyvar,$val){ $$anyvar=$val; } setval('myvar',$whatever); how to do in javascript ... I thied window.anyvar= and this[anyvar] and several other combinations but no joy Edit: fixed, my bad, was being a muppet, was calling setvar(varname,val) instead of setvar('varname',val); Very new to javascript, so I apologize in advance. I honestly tried to figure this out on my own, and I'm just not able. I'm trying to create a family tree online that has several other related family charts. I want each person's name and birth year to be stored in javascript variables, then I want to be able to just go through the tree, and put the persons name once, and have it put the appropriate name and birthyear in the little boxes that the css is creating. In the js file... I would do this for each family member. Code: var johnname = "John Smith"; var johnbirthyear = "Jan 1 1930"; var janename = "Jane Doe"; var janebirthyear = "Jan 1 1940"; var mikename = "mike wilson"; var mikebirthyear = "Jan 1 1950"; var saraname = "sara johnston"; var sarabirthyear = "Jan 1 1960"; In the HTML file... Code: <div id = "boybox"> <script type="text/javascript"> id = "john"; <!-- this is the only thing I want to have to change --> name = id+"name"; document.write(name); </script> <div id = "year"> <script type="text/javascript"> birthyear = id+"year"; document.write(birthyear); </script> </div> </div> So I thought I had it all figured out. I thought that the above would take the id of John that I added, go to the line that sets the name, add john to the word name, and then document write the variable of johnname from the js file. I know you're laughing at me because of course it instead made the value of name to johnname, then wrote the word johnname in the box. Can anyone point me in the right direction please? ultimately I want to go through and be able to just type the persons name in the html for that box once, and have it update with their appropriate info. Thanks, and sorry for such a rookie question. Hi, I have a programing problem that have been around for ages. I have search on google using several expressions and words and after hours of digging i'm still unable to do it. I would like to get a value from a HTML page hosted remotely with an inconstant value. Then define this value and name as a javascript variable and apply or show in my page. Thanks for all the help P.S. Is there any way to make a domain lookup in javascript? I mean a user enters a domain and the script converts to an ip and shows to the user. If not thanks, probably it can only be done in the server side... Hello I have a php page in which I declared a js variable... right at the top of the page... <script type="text/javascript"> var tester = 0; </script> Later in the page I test this variable... <script type="text/javascript"> if (tester==1){ do some stuff!! } </script> But I keep getting an error variable _tester undefined Am I missing something obvious... I am new to js... but this seems really straightforward I don't know how I should do ? Quote: <html> <head> <script type="text/javascript"> function add(a,b){ y=a+b return y } var aaa = add(one,two) //one needs to get somehow get the value of yil, in this case 10 var one = function reas(){i=10;if(i<10){yil = 15}; else{yil = 10; yil = one;}; var two = 20; document.write(y) </script> </head> </html> also why doesn't this work? Quote: <html> <head> <script type="text/javascript"> function adder(a,b){ var k=a+b; return k } var hes=adder(5,kol); kol=40; alert(hes); </script> </head> </html> you cannot have variables in callback functions? Hi! I have a javascript in the head of the document which has a variable named "ref2" ... ref2 is already working as I can see its value working in another function. I need to send this variable as the value of a hidden field in the form which is in the body of the document. This is my JavaScript Code: Code: function WriteContactFormStatement1 () { var ContactFormValue = ref2; document.write('<input type="hidden" name="UReferrersName" value="' + ContactFormValue + '" />'); } var WriteContactFormStatement = WriteContactFormStatement1 (); And at the end of my form, before the submit button, I have the following code: Code: <!-- START -- Javascript to print the statement for UReferrersName --> <script language="JavaScript" type="text/JavaScript"> //WriteContactFormStatement(); document.write (WriteContactFormStatement); </script> <!-- End -- Javascript to print the statement for UReferrersName --> When I execute the form, it doesn't work the way it should, plus, gives me a word "undefined" next to the "Submit" button ..... Please help !... - Xeirus. Hello everybody I have a problem with Java Script damned I want to add the values of several variables in one variable and then use this variable, which contains the values of variables You can see the following example HTML Code PHP Code: <input type="text" name="txt1" /> <br/>age <input type="text" name="txt2" /> <br/><br/> <input type="button" name="submits" value="send"/> Javascript Code PHP Code: field = document.getElementsByName('txt1')[0]; field2 = document.getElementsByName('txt2')[0]; submit = document.getElementsByName('submits')[0]; data = 'data=' + field.value + '&data2=' + field2.value + '&submits=' + submit.value; document.getElementsByName('submits')[0].onclick = function(){ alert(data); } After executing this code I find that the variables are not displayed values As in the following picture I want to know what the cause of this problem ? If I manually write out "2/22/2012 4:00 PM" in TargetDate, I get the correct result for what I want to do (a countdown). But I want the countdown to always be the current day at 4pm. So I tried the code below thats commented, but it is not working. New to javascript, still reading the books, just hoping for some guidance on this. Code: Next Update: <script language="JavaScript"> var currentTime = new Date() var month = currentTime.getMonth() + 1 var day = currentTime.getDate() var year = currentTime.getFullYear() TargetDate = "2/22/2012 4:00 PM"; //TargetDate = "document.write(month + "/" + day + "/" + year) + 4:00PM"; BackColor = "white"; ForeColor = "red"; CountActive = true; CountStepper = -1; LeadingZero = true; DisplayFormat = "%%H%% H, %%M%% M, %%S%% S"; FinishMessage = "Forecasts posted"; </script> <script language="JavaScript" src="countdown.js"></script> This might be a stupid question, but is there any memory usage difference between var variable1, variable2; and var variable1; var variable2;? I'm learning how to use faster code hence the question.
Hello I have a piece of javascrip that refreshes the page: ---------- Code: <script type="text/javascript"> <!-- Begin function reFresh() { location.reload(true) } /* Set the number below to the amount of delay, in milliseconds, you want between page reloads: 1 minute = 60000 milliseconds. 2 minutes = 120000 milliseconds 5 minutes = 300000 milliseconds*/ window.setInterval("reFresh()",20000); // End --> </script> -------- I am new to javascript and wanted to use an html options menu in order to be able to choose the refresh interval: Code: <SELECT NAME="refreshtime"> <OPTION VALUE="60000">1 min</option> <OPTION VALUE="120000">2 min</option> <OPTION VALUE="180000">3 min</option> <OPTION VALUE="240000">4 min</option> </SELECT> I know that I have to pass a variable to the function. I have tried several variations but none have worked. I have mostly received a "done with errors" warning. Any help would be appreciated. Thanks Zam Hi, I want to write some javascript code that uses arrays, I have a list of arrays named array1, array2, array3 etc. I want to perform a function on each of these arrays. I wanted to have a variable for the number after array so this is what I have: <code> var array1 = new Array ("1","2","3","4","5"); var array2 = new Array ("5","6","7","8","9"); for (var i=1; i<=2;i++){ document.writeln(("array"+i)[1]); } </code> the problem is it gives me the letters in the string array instead of the array values. How do I get javascript to treat ("array"+i) as array1? Can anyone tell me of how to take or assign a javascript variable into php.
I wrote a script: when the same button is clicked for the first time, it should give a message "Hello World", for the second time "hello Earth". The script is not working. I don't want anybody to re-write the script, but to look at how i define variables and tell me where I am wrong. I think, this is where the main error is. my current script just outputs the message "hello world". my assumption is that functions can alter the value of a global variable. Thank you very much. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> title</title> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <script type="text/javascript"> var count=0; function changePar() { if(count===0) first(); if(count===1) second(); } function first() { document.getElementById("changingParagraph").innerHTML="Hello World"; var count=1; } function second() { document.getElementById("changingParagraph").innerHTML="Hello Earth"; var count=0; } </script> </head> <body> <button onclick="changePar()">Click Here</button> <p id="changingParagraph"></p> </body> </html> Hi All Please could any one shed some light on the values of thirdVar fourthVar and fifthVar. Am i correct to say that value of thirdVar is o cromwell Any help and explanation would be great thanks. var firstVar = 'oliver' var secondVar = 'cromwell' var thirdVar = firstVar.charAt (0) + '. ' + secondVar var fourthVar = thirdVar.length var fifthVar = 'The last character is' + thirdVar.charAt (fourthVar) + '!' hello i am editing a javascript game and im trying to get a heading (h1) to display the value of a variable in a javascript function however everything i have tried always causes an error. Any help will be apreciated. Noob here. Please bear with me.http://www.codingforums.com/images/smilies/tongue.gif <span title="this is the title">....</span> I need to use variables for the title instad of text. Please advise. Thank you. I hope someone can help me! I have a website that sells a product through a third party merchant - ie a customer clicks my "buy now" button and they are transfered to the merchants payment processing page. once the transaction is complete the customer is sent back to my thank you page where I give them some extra stuff for free. All pretty normal I guess. The problem is this - The merchant sends back some url parameters when they transfer the customer to the thank you page and I would now like to use the "customer name" parameter to personalise the thank you page to test if this makes any difference to my return rate. Now, whilst I am not a complete newbie I haven't got a clue how to achieve this. What I want to do is have the page display: "Hello [customer] .....etc..." The customer name parameter is passed as "cname" and is one of about a dozen passed seperated, presumably, by "&" Thanks for any help! Paul Code: <script language="javascript" type="text/javascript"> function limitText(limitField, limitCount, limitNum) { if (limitField.value.length > limitNum) { limitField.value = limitField.value.substring(0, limitNum); } else { limitCount.value = limitNum - limitField.value.length; } } </script> <textarea name="txt_area" rows="3" id="txt_area" class="style3" onKeyDown="limitText(this.form.txt_area,this.form.countdown, 500);" onKeyUp="limitText(this.form.txt_area,this.form.countdown, 500);" cols="20"></textarea><br> <font face='Arial' size="1" color='#336600'>(Maximum characters: 500)<br> You have <input readonly type="text" name="countdown" size="3" value="500"> characters left.</font> </td> This works great BUT, the value 500 (in 4 places in the above HTML) is a constant. I need this value to be set to a default when the page loads, but I have onclick events that change the style of the textarea and in doing so, I need the maximum allowed characters to change. So I need the constant value 500 to be a variable that changes with my onclick event AND gets initially set (I'm guessing) on page load..... I just do not know how to change this constant into a variable and make that variable change with onclick. Thank you. Hi, I'm trying to get variables out of an iFrame for my JavaScript function. Is it possible to use an onload parameter to call the JavaScript function to run after it has loaded? If there is a better method to get remotely created variables into a JavaScript function, besides using the url, please let me know. Thanks |