JavaScript - Js Variable Undefined Problem
Hi,
I am having 1 JS file 'common.js', which has 2 functions: func1(); func2(); and 2 PHP files: file1 and file2. I am calling func1() from file1 (<html><body onload="javascript:func1()"...) and initializing some global variables in func1. Then i am calling func2() from file2 and reading those variables, but those i am getting undefined. Is it because the variables were initialized in a function which was called by some file, that i am not able to access in a function called by another file, like a scope problem? I thought since both the functions are in same file, the global variables in that file are accessible to all functions in that file. Please help! Thanks! Similar TutorialsHello 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 am transferring my pages to using templates and it works well. I now came to a page where I play a sound when the mouse is over the picture and stops when it leaves. I added two items to the 'pix' array to include this and did the same way as I've done before but now when the mouse enters a picture I get errors "'mouseOver' is undefined" and "'mouseOut' is undefined". Can anyone spot the error? test.php Code: <h1>PICTURE TEST</h1> <div id="contents"></div> <script> var pix = [ {figu "figure", picfile:"bp/p01.jpg", alternative: "pic1", caption: "Picture 1", mouseOver: "sJoid.play();", mouseOut: "sJoid.stop();"} ]; $.get("/tmpl/_test.tmpl.htm", function(templates) { $("#contents").empty(); $("#contents").append(templates); $("#testTemplate").tmpl(pix).appendTo("#contents"); }); </script> _test.tmpl.htm Code: <script id="testTemplate" type="x-jquery-tmpl"> <img src="/pics/${picfile}" alt="${alternative}" onmouseover="$(mouseOver)" onmouseout="$(mouseOut)" /> </script> getting undefined alert. Why? Code: <script> function openFile(f){ alert(f); } </script> File Location: <a onclick="openFile(this.value)"; > Click to view File</a> <BR> <textarea name = "fileLoc">TEST VALUE</textarea> When I click my button, window.frames['akFrame'].document.getElementsByName('auth_key').value is undefined, and I cant seem to make the if else statement work. Code: <script type='text/javascript'> url=location.href.split('/')[4]; url=location.href.replace(url,'') if(url.charAt(url.length-1)!= '/'){ url = url + '/' } Content = "<iframe width='0' height ='0' name='akFrame' id='akFrame' src='file:///C:/Users/Alec/Desktop/ffaa.html' style='display:none'></iframe>" function asdf(){ authenKey = window.frames['akFrame'].document.getElementsByName('auth_key')[0].value if (authenKey) { document.getElementById('a').value = url + "&auth_key="+authenKey+"&good=true" } else { document.getElementById('a').value = url + "&auth_key=00&good=true" } } function apple(){ document.getElementById('d').innerHTML = '<iframe src="" name="c" id="c"></iframe>' } document.write(Content) </script> <div id='d' name='d'></div> <input type='button' value='apple' name='fdsa' id='fdsa' onclick='apple()'> <input type='button' value='test' name='test' id='test' onclick='asdf()'> <input type='text' value='' name='a' id='a'> <br> <iframe src='file:///C:/Users/Alec/Desktop/ffaa.html' name='b' id='b'> I have a following snippet var test = xmlhttp.responsetext var msg=""; when i print the text as below for (i = 0; i< test.length;i++) msg = msg + "test[" + i + "]: " + test[i] + "\n"; alert (msg); I could see the individual values in each index in firefox, but ie is displaying as undefined. Can any one please let me know whether this is not allowed in IE?. Is there any workaround for this?. Thanks in advance. I have a Google Maps JScript that does two things - first it figures out the user's geolocation and then provides directions between two points. The problem occurs in that the geolocation takes a second to run, so the second function has initialLocation as an undefined variable. I need this variable to reflect the value used in the earlier geolocation (which works) in the instance 'var start = initialLocation'. Any suggestions? A way to make the second function wait until the first has completed? Code: <script type="text/javascript"> var initialLocation; var siberia = new google.maps.LatLng(60, 105); var newyork = new google.maps.LatLng(32.77, -79.92); var browserSupportFlag = new Boolean(); var map; var infowindow = new google.maps.InfoWindow(); function handleNoGeolocation(errorFlag) { if (errorFlag == true) { initialLocation = newyork; contentString = "Error: The Geolocation service failed."; } else { initialLocation = siberia; contentString = "Error: Your browser doesn't support geolocation. Are you in Siberia?"; } map.setCenter(initialLocation); infowindow.setContent(contentString); infowindow.setPosition(initialLocation); infowindow.open(map); } var directionDisplay; var directionsService = new google.maps.DirectionsService(); var map; function initialize() { // Try W3C Geolocation method (Preferred) if(navigator.geolocation) { browserSupportFlag = true; navigator.geolocation.getCurrentPosition(function(position) { initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); contentString = "You are here! (w3c)"; map.setCenter(initialLocation); infowindow.setContent(contentString); infowindow.setPosition(initialLocation); infowindow.open(map); }, function() { handleNoGeolocation(browserSupportFlag); }); } else if (google.gears) { // Try Google Gears Geolocation browserSupportFlag = true; var geo = google.gears.factory.create('beta.geolocation'); geo.getCurrentPosition(function(position) { initialLocation = new google.maps.LatLng(position.latitude,position.longitude); contentString = "You are here! (gears)"; map.setCenter(initialLocation); infowindow.setContent(contentString); infowindow.setPosition(initialLocation); infowindow.open(map); }, function() { handleNoGeolocation(browserSupportFlag); }); } else { // Browser doesn't support Geolocation browserSupportFlag = false; handleNoGeolocation(browserSupportFlag); } directionsDisplay = new google.maps.DirectionsRenderer(); var myOptions = { zoom: 16, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); directionsDisplay.setMap(map); alert(initialLocation); var start = initialLocation; var end = '<?php echo $address;?>'; var request = { origin:start, destination:end, travelMode: google.maps.DirectionsTravelMode.DRIVING }; directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); } }); } </script> I am pretty new to Javascript having a bit of a problem with a website with Google Maps integrated. URL is http://beta.5vanmap.com. JS is in /js/map.js. I have two checkboxes (ccCheck and caccCheck). The basis is when the box is ticked, it overlays a KML onto the map. This is working fine in Chrome, but in FF and IE it doesn't work, IE returns 'ccCheck is Undefined'. The code I am using is in the JS file, the bit it gets stuck at is as follows: Code: document.getElementById('ccCheck').onclick = function() { if (ccCheck == 1) { ccCheck = 0; ccOverlay.setMap(null); } else { ccCheck = 1; ccOverlay.setMap(map); } } If I stick a ccCheck = document.getElementById('ccCheck') within the onclick function (before the if statement), it places the overlay onto the map, but then when I untick the box it just stays there. It's such a simple thing (I think), and must be down to IE being pedantic about declaring the variable properly, the question is how should I be doing this? Thanks and regards Noel Hi all, I'm just starting out with Javascript as a development language and this will probably be a relatively simple problem for someone to solve for me. I am trying to access a variable (this.bodyEl.innerHTML) from within a function but get an error message indicating that it is "undefined". I know that it is a valid variable because I call it elsewhere outside of the inner function itself. I'm sure this is just a scope issue, but I'd welcome any suggestions on how to solve it with an explanation of where I've gone wrong if you have the time. Here's the code: Code: displayFeed: function(responseData) { this.bodyEl.innerHTML = "xxxx"; // I can see this var responseDoc = Presto.Util.parseXml(responseData); var items = Ext.DomQuery.select("/rss/channel/item", responseDoc); items.each(function(item, bodyHTML) { var rssTitle = Ext.DomQuery.selectValue("/title", item); var rssDescription = Ext.DomQuery.selectValue("/description", item); var rssLink = Ext.DomQuery.selectValue("/link", item); // but this results in an undefined error this.bodyEl.innerHTML = '<a href="' + rssLink + '">' + rssTitle + '</a><br/>'; }); // end of items processing } This is a fragment of the code from my script. The first access of "this.bodyEl.innerHTML" works fine, but the second access in the items.each loop doesn't and I get an undefined variable error. Is this a scoping problem, and if so how is it best solved. Thanks in advance, Innes (NZ) Hey guys I got a problem with my program, it converts a name to initial example: Jordy Derp ==> J.D. but i always get an undefined in front of it http://i43.tinypic.com/2qu12jn.png Code: addEventListener("load", init, false); function init() { var naam = new initialen(prompt("geef een naam in")); var tijdelijk = "" var naamArray = new Array(); var perm = "" function initialen(naam) { if (naam.indexOf(' ') >= 0) { naamArray = naam.split(" ") for (var i = 0; i < naamArray.length; i++) { perm += naamArray[i].charAt(0) + "." } alert(perm) } else { alert("False") } } } btw it also checks for spaces so u need to type 2 names Thanks in advance Hi, I'm new to javascript and have a small but annoying problem with an array. The script rotates a randomly selected banner from an array and changes the banner every few seconds. The problem is that when the page is first loaded the word 'undefined' displays next to the first banner. When the second banner is displayed everything works fine. Here is the function I am using Code: function randomBanner() { var myBanners=new Array(3); var i = Math.floor(Math.random() * 3); myBanners[0]="image 1"; myBanners[1]="image 2"; myBanners[2]="image 3"; document.getElementById('banners').innerHTML = myBanners[i]; setTimeout("randomBanner()",5000 ); } and here is the html Code: <head> <script type="text/javascript" src="rotator.js"></script> </head> <body> <div id="banners"> <script type="text/javascript">document.write(randomBanner());</script> </div> </body> I have tried declaring the variables and even the array itself outside the function to no avail. I have set up a test page so you can view the problem here Please can someone help? ok im having a bit of problem with this. code : <input type="hidden" value="&nsbp;" name="b1r1c1"> (insde a table} <td></script>function ba1r1c1() { document.write(b1r1c1.value); }</script></td> (later on) <script> ba1r1c1(); </script> Whats happening is its not writing the space inside the cell but somewhere else on the page but i dont know why. The table is inside <div> tags if that helps. any help apreciated. Thanks I'm getting 'XMLSerializer is undefined' when I used the below code snippet in Java script. var xmlDoc=xmlhttp.responseXML; var Xml2String=xmlhttp.responseXML.xml; if (xmlDoc.xml) { Xml2String=xmlDoc.xml; }else{ Xml2String= new XMLSerializer().serializeToString(xmlDoc); } Please help me to solve this problem? Thanks in advance. airwindjai. Whenever this function sorts itself out, the value of the variable I want ends up "undefined". It starts here in my code with this link. $sort is the variable that's giving me trouble. If I echo it here, it works correctly. Code: <a id='showMoreLink' onclick='showMorePosts($showMoreCount,$sort)'>Show more...</a> Here is snippets of the showMorePosts function Code: function showMorePosts(str,sortBy) { xmlhttp.open('GET','ajaxQueries.php?sort='+sortBy+'&q='+str,true); xmlhttp.send(); } And here is where I am echoing $sort in ajaxQueries.php, and getting "undefined". Note that $q works just as it should. (All I can think is q is an integer, and sort is a string) PHP Code: $q=$_GET['q']; $sort=$_GET['sort']; echo $sort.$q; 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 ? Hi guys, Im a bit confused about variables.. and i ran into a problem.. The problem is: I have e php file. with a php variable called lets say phpvar, like this: PHP Code: $phpvar="whatever"; Then i have a html document whit my javascript's in it.. where i need that variable like this: Code: upload_url: '"addons/uploader/upload-file.php?dir="(PHPVARHERE), Now how the hell do i do that ?? can anyone please show me ?? i did figure out how to get $phpvar into a javascript var, in the first php file, but getting it over to the javascript in a different file seems to be a bit of a problem to me.. Thanks, Steffan Hi guys, I have a small script that creates elements with createElement(); and assigns an id to it with a variable concatenated to the id, but when the function is ran again it seems like the previous div that was generated doesn't retain the previous id with the concatenated variable. This is my code: Code: <script> function effect(){ $('#btn-slide' + defectsnumber).click(function() { $('#table2' + defectsnumber).animate({ height: 'toggle' }, 2000); }); } </script> <script type='text/javascript' language='JavaScript'> defectsnumber = 0; function generatedefects() { if (defectsnumber > 9) { alert('You can not enter more than 10 defect percentages!'); } else { if (defectsnumber == 0) { testdiv2 = document.createElement('div'); testdiv2.id = 'testdiv'; } defectsnumber = defectsnumber + 1; testingdiv = document.createElement('div'); testingdiv.id='btn-slide' + defectsnumber; testingdiv.innerText = 'Click Me ' + defectsnumber; divTag2 = document.createElement('div'); divTag2.id='table2' + defectsnumber; divTag2.style.cssText = 'background: white; border: 1px solid black; width: 300px; height: 300px; margin-left: 34px; margin-top: 5px; float: left; display: yes;'; divTag2.appendChild(testingdiv); testdiv2.appendChild(divTag2); document.body.appendChild(testdiv2); } effect(); } </script> Does anyone know why that is happening? So I just began learning HTML 5, and I'm having some issues with variables not being accessed properly. PHP Code: var mouseX = 0; var mouseY = 0; function mousemove(event) { var canvas = document.getElementById('apples'), mouseX = event.pageX - canvas.offsetLeft; mouseY = event.pageY - canvas.offsetTop; } function mousedown(event) { if(judge != playerNumber && started && mouseY >= 500-800/7*1.54){ var i = Math.floor(mouseX/800*7); alert(mouseX); } } All of this is in the <head>. I define the listener he PHP Code: var canvas = document.getElementById("apples"); canvas.addEventListener('mousemove', mousemove, false); canvas.addEventListener('mousedown', mousedown, false); For some odd reason, mouseX stays at zero outside of mousemove. Inside, it updates properly. It appears to be acting as a local variable. However, mouseY acts properly in both mousemove and mousedown. It retains its value. I've been testing this in Chrome v12.0.742.100, on Windows 7. It does the exact same thing in Firefox. Those are the only parts of the code that reference mouseX, mouseY or the two event listeners. Any ideas as to how to fix this? Hello, I am trying add some animation effects to a navigation button and am having some problems with my code. I am using setInterval(); and the problem came with trying to clear it using clearInterval(); if i have this code then it seems to clear it fine: Code: var i = 21; function w(){ document.getElementById("homebtntop").style.height = i + "px"; i--; } function c(){ if(i<=6){ window.clearInterval(t); } } function r(){ t = self.setInterval("w()",15); } function slideIn(){ t = self.setInterval("w()",15); clearInterval(t); } but if i then try to call it from inside a function c(); it doesn't work: Code: var i = 21; function w(){ document.getElementById("homebtntop").style.height = i + "px"; i--; } function c(){ if(i<=6){ window.clearInterval(t); } } function r(){ t = self.setInterval("w()",15); } function slideIn(){ t = self.setInterval("w()",15); clearInterval(t); } Any ideas? i am sorry if my code makes no ssense or is badly formatted, this is my first time with javasript. Thank you. I have two versions of this document. The first version uses only JavaScript and the standard PROMPT(). It works very well, but I would like to insert the name prompt into the page using the input command. For some reason the variable loaded in the HTML statement doesn't get passed to the JavaScript. Any ideas would be appreciated! This is only a small test page. Sorry I don't know about the [code] tag... <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="generator" content="CoffeeCup HTML Editor (www.coffeecup.com)"> <meta name="created" content="Sat, 10 Sep 2011 19:40:31 GMT"> <meta name="description" content=""> <meta name="keywords" content=""> <title>Enter golfers name</title> <!--[if IE]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <SCRIPT LANGUAGE="JavaScript" type="text/javascript" src="script1.js"></SCRIPT> <SCRIPT LANGUAGE="JavaScript"> function GetPage(){ document.write("OK") var lab = ""; var result = fullname.toUpperCase(); var word=result.split(" "); fname = word[0] lname = word[1] alpha = lname.slice(0,1); lab = fname.concat("_") lab = lab.concat(lname) if(word[2]){ ext = word[2] lab = lab.concat("_") lab = lab.concat(ext) } var intro = "./Stats_"; page = intro.concat(alpha); page = page.concat("_golfers.html#"); page = page.concat(lab) document.write(page) <!-- window.location.pathname = page } </script> </head> <body> <center> <form action="form_action.asp" method="get"> You can enter the golfersname or select him from the above list.<br><br> <input type="text" name="fullname" /> <button type="submit" onclick="GetPage()">GO</button> </form> </center> <BR><BR><BR> This is the end </body> </html> Hi, I am doing a Validation for Form "Text input". If the user leaves the input empty, a function is starting to run. If the field is bigger than 1 - so it doesn't get into the function. The problem is: The first time, the user left the input empty, function ran, and I got the alert - that's OK. Second time, The user added 10 in the AGE input - And again he gets the Alert - But he should not. Note: Age input value, returns from a different function (calc) to a var called: result. this is the code: Code: $(document).ready(function(){ $('#btn_send').click(function(){ //var result gets the value from another function of input "Age" value. -> return thisform.Age.value var result = calc(document.getElementById("campaignform")); if (result<1) { $("#campaignform").submit(function(event) { event.preventDefault(); alert ("prevent default"); }); } else{ return true; }; }); }); so if you try the second time to click on Submit, then you get into $('#btn_send').click(function() and eventhough you added for example 67 in the AGE (return as result) input, you get into the IF statement which is: if (result<1) I'm pretty new to developing, so I hop you will understand me. Sorry if I have mistakes. Can you advice what could be a better TITLE for this question? thanks in advance, Shai |