JavaScript - Undefined Variable Error, Even Though Variable Is Defined
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 Similar TutorialsI'm having some issues with firefox, chrome seems to work ok. Firebug is giving me an error stating country is not defined. The line it's saying it's on is where the function for an ajax call to populate a select input on page load. Here's the script that sets up the functions to call and fill the state and city values: Code: <script src="/components/com_helloworld/js/request.js"> /**************************************************** * Ajax call to fill city values ****************************************************/ </script> <script> function handleOnChange(dd1) { var idx = dd1.selectedIndex; var val = dd1[idx].text; var par = document.forms["cbcheckedadminForm", "adminForm"]; var parelmts = par.elements; var cb_statesel = parelmts["cb_state"]; var country = val; var directory = ""+document.location; directory = directory.substr(0, directory.lastIndexOf('/')); Http.get({ url: "./components/com_helloworld/js/regvalues/states/" + country + ".php", callback: fillcb_state, cache: Http.Cache.Get }, [cb_statesel]); } function fillcb_state(xmlreply, cb_stateelmt) { if (xmlreply.status == Http.Status.OK) { var cb_stateresponse = xmlreply.responseText; var cb_statear = cb_stateresponse.split("|"); cb_stateelmt.length = 1; cb_stateelmt.length = cb_statear.length; for (o=1; o < cb_statear.length; o++) { cb_stateelmt[o].text = cb_statear[o]; } } else { alert("Cannot handle the Ajax call."); } } function handleOnChange2(dd1) { var idx = dd1.selectedIndex; var val = dd1[idx].text; var par = document.forms["cbcheckedadminForm", "adminForm"]; var parelmts = par.elements; var cb_citysel = parelmts["cb_city"]; var state = val; var directory = ""+document.location; directory = directory.substr(0, directory.lastIndexOf('/')); Http.get({ url: "./components/com_helloworld/js/regvalues/" + state + ".php", callback: fillcb_city, cache: Http.Cache.Get }, [cb_citysel]); } function fillcb_city(xmlreply, cb_cityelmt) { if (xmlreply.status == Http.Status.OK) { var cb_cityresponse = xmlreply.responseText; var cb_cityar = cb_cityresponse.split("|"); cb_cityelmt.length = 1; cb_cityelmt.length = cb_cityar.length; for (o=1; o < cb_cityar.length; o++) { cb_cityelmt[o].text = cb_cityar[o]; } } else { alert("Cannot handle the Ajax call."); } } </script> And here's how it's being triggered on page load: Code: <script> function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } } addLoadEvent(function() { ajaxFunction(document.getElementById('country').value); handleOnChange(country); setupDependencies('cbcheckedadminForm', ''); handleOnChange2(cb_state); }); </script> I'm not sure why it says it's not defined as it clearly is. This error is causing the dependent drop down script to not work in firefox causing the child dropdowns to not hide. I did notice something odd though, if I remove the doctype line it works ok. I did this as firebug was throwing an error on another page claiming it had a syntax error so obviously something somewhere is messed up. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>" dir="<?php echo $this->direction; ?>"> When the doctype lines are removed firebug throws this error: window.document.forms[arguments[i]] is undefined [Break On This Error] for(var j = 0, e = window.document...ts[i]].elements; j < e.length; ++j) { in formmanager.js. Hi, Using a while loop in a function, I am trying to test an input character against a stored string of characters. I want the function to return the input character only if it is not in the stored string of characters. The code I've prepared is as follows: Code: <SCRIPT language = "JavaScript"> var storedLetters = 'sideways'; function requestLetters(aString) { var validLetter =''; var inputLetter = window.prompt('Please input a single lower-case letter', ''); while (storedLetters.indexOf(inputLetter) != -1) { inputLetter = window.prompt('You have already tried ' + inputLetter + ' . Please try another' + ' letter.'); } validLetter = inputLetter; return validLetter; } requestLetters(storedLetters); document.write(validLetter); </SCRIPT> The code works fine if I remove it from the function wrapper but if the function is called I keep getting an error message that the variable validLetter is not defined. Can anyone see why this is the case? Thanks. Hi all, I am relatively new to java; hence I know the basics, but have been thrown into trouble because I am currently working with a cms system that doesnt keep within the correct name conventions (pre defined). Within a form, I simply want to set a date to todays date: <script type="text/javascript"> function initdt(mf) { var t = new Date; mf.01-date.value = t.getDate(); mf.02-month.value = t.getMonth() + 1; mf.03-year.value = t.getFullYear(); } onload="initdt(document.WBForm);" </script> This works perfect on a form I create, but sadly I must use a form within a pre defined system that uses "01-date" Is there a way around this? A simple way of setting 01-date to t.getDate(); Your help will be very much appreciated Regards Damon Simpson Hi Guys, I have a new problem My site is run on wordpress, but I'd like to customise the menu so that if the user is logged in the menu displays "Logged In" and if they are not it displays "Log In". Normally I would just use an if statement in PHP to output the required html, but as I can't use PHP code in the menu item I need to use Javascript. So, the way I figured this would work is: 1) PHP code in the header checks to see whether the user is logged in 2) This code then outputs JS to define a variable (varCheckLogin) 3) JS within the menu checks varCheckLogin and outputs the html i want This sounds good hopefully. Unfortunately this isn't working at the moment. The code I have is: HEADER: (I know this works as the variable is being output correctly in the source code) Code: <?php if (is_user_logged_in()) { echo '<script type="text/javascript"> varLoginCheck = "Yes"; </script>'; } else { echo '<script type="text/javascript"> varLoginCheck = "No"; </script>'; } ?> MENU ITEM: Code: <script> if (varLoginCheck = "No") { document.write('<span class="mmLogin">Log In</span>'); } else { document.write('<span class="mmLogin">Logged In</span>'); } </script> I put an alert in the menu item and it always sees varLoginCheck as "Yes". Any ideas why this could be? All help is much appreciated. Thanks Sam 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> 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> i keep getting error Call to undefined function codeandurl() below is my code PHP Code: <?php $value= strip_tags(get_field('link',$post)); $resultid=get_field('resultid',$post); codeandurl($resultid,$value); ?> <div id="result"></div> <script type="text/javascript"> function codeandurl(resultid,url){ $( "#result" ).text(resultid); $( "#result" ).dialog({ modal: true, buttons: { Ok: function() { $( this ).dialog( "close" ); } } }); window.open(url); return false; } </script> 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'> 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! 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 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 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) 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... Hi, I am looking for some help with function below, the $date variable will for months 01-09 return a value of 1-9 leaving out the 0 numerator Code: function reformatDate($Date) { var $date = $Date; months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; var parts = $date.split("/"); var m = parts[0]; for ( var i = 0; i < months.length; i++ ) { if (months[i] == m ) { var month = i; } } $date = parts[2] + "-" + (month+1) + "-" + parts[1]; // +1 needs to be appended to month as JavaScript month starts at 0 _log("Date " + $date); //test date is in correct format return $date; } so in above example if i pass a date 01/02/2015 it will return 2015-1-02 whereas i want it to return 2015-01-02 for the purposes of the function i need the $date to return 01,02,03 etc also can anyone explain why the zero is dropped before each number? Reply With Quote 01-22-2015, 03:39 PM #2 sunfighter View Profile View Forum Posts Senior Coder Join Date Jan 2011 Location Missouri Posts 4,830 Thanks 25 Thanked 672 Times in 671 Posts Problem is he Code: for ( var i = 0; i < months.length; i++ ) { if (months[i] == m ) { var month = i; // YOU SET THIS TO A SINGLE DIGIT. USE var month = months[i]; } 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. 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? Whenever I try to compile a script I wrote, I get the error, "class, interface, or enum expected" and it points to a spot in my script that I don't think should create an error... I've tried changing different things in the line it points to, but it doesn't help. Here's are some of the errors: Code: Code: var it = 0; var udt = new array(10); for(it = 0, it < udt.length, it++){ switch(it){ case 0: udt[it] = prompt("Type a name", ""); case 1: udt[it] = prompt("Type a verb", ""); case 2: udt[it] = prompt("Type an adverb", ""); //case 3: udt[it] = prompt("Type a //case 4: udt[it] = prompt("Type a //case 5: udt[it] = prompt("Type a //case 6: udt[it] = prompt("Type a //case 7: udt[it] = prompt("Type a //case 8: udt[it] = prompt("Type a //case 9: udt[it] = prompt("Type a //case 10: udt[it] = prompt("Type a } } document.write(udt[0] + udt[1] + "away as" + udt[2]); Errors: Code: story.java:1: class, interface, or enum expected var it = 0; ^ story.java:2: class, interface, or enum expected var udt = new array(10); ^ story.java:4: class, interface, or enum expected for(it = 0, it < udt.length, it++){ ^ story.java:17: class, interface, or enum expected } ^ I've looked over the first one and I have no idea why that is an error. If the reason is obvious to you, please be polite. I've only been using javascript for about 2 days. 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; Hi ,, im trying to access cells in the excel , but when iam using variabel inActiveSheet.Cells(1,k) im getting error "Expected :". Could you please help me. Big Thanks in Advance <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1250" /> <script> function CreateExcel() { var ExcelSheet; var i=0; var ExcelApp = new ActiveXObject("Excel.Application"); //ExcelSheet = new ActiveXObject("Excel.Sheet"); //ExcelSheet.Application.Visible = true; //ExcelSheet.ActiveSheet.Cells(1,1).Value = "C11"; //ExcelSheet.ActiveSheet.Cells(1,2).Value = "C12"; //ExcelSheet.SaveAs("C:\\Book1.xls"); ExcelApp.Visible = false; var i=1; for(i=0;i<10;i++) { var k=i; document.write(ExcelApp.Workbooks.Open("C:\\wiki estimation.xls").ActiveSheet.Cells(1,k).Value); } ExcelApp.Quit(); //ExcelSheet.Application.Quit(); } </script> <input type=button name=mybutton value=ExcelSheet onclick="CreateExcel()"> </head> <body> </body> </html> |