JavaScript - Need Help Accessing Object
Hello,
I have a multi-dimensional object, derived from JSON returned by the Foursquare API. The object has the following structure (as printed using a print_r type method from http://www.openjs.com/scripts/others...hp_print_r.php PHP Code: '0' 'id' => "27110xxx" 'created' => "Sun, 11 Apr 10 15:09:45 +0000" 'timezone' => "America/New_York" 'user' ... 'id' => "48xxx" 'firstname' => "Barry" 'lastname' => "xxx" 'photo' => "http://playfoursquare.s3.amazonaws.com/userpix_thumbs/4abb5bxxxxxx.jpg" 'gender' => "male" 'display' => "xxxx. @ [off the grid]" '1' ... 'id' => "2538xxxx" 'created' => "Wed, 07 Apr 10 13:24:41 +0000" 'timezone' => "Europe/London" Could anyone tell me the best way to access its elements? I have this so far which gets the required values, but I want to preserve the order ie. get the data from the first element in the object first, then move to the next - each element represents a user so I want to keep their data separate. PHP Code: /* This is a custom function which has the same function as print_r */ function dump(arr,level) { var firstName, lastname, geolat, geolong, photo; var dumped_text = ""; if(!level) level = 0; //The padding given at the beginning of the line. var level_padding = " "; for(var j = 0; j < level + 1; j++) level_padding += " "; if(typeof(arr) == 'object') { //Array/Hashes/Objects for(var item in arr) { var value = arr[item]; if(typeof(value) == 'object') { //If it is an array, dumped_text += level_padding + "'" + item + "'\n"; dumped_text += dump(value,level + 1); } else { dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n"; } if (item == 'firstname') { firstname = value; document.write("First name: " + firstname + "<br />"); document.write(item); } if (item == 'lastname') { lastname = value; document.write("Last name: " + lastname + "<br />"); document.write(item); } if (item == 'geolat') { geolat = value; document.write("Latitude: " + geolat + "<br />"); document.write(item); } if (item == 'geolong') { geolong = value; document.write("Longitude: " + geolong + "<br />"); document.write(item); } } } else { //Stings/Chars/Numbers etc. dumped_text = "===>"+arr+"<===("+typeof(arr)+")"; } return dumped_text; } var myObj = <?php echo json_encode($checkin); ?>; alert(dump(myObj)); Sorry for the bloated code, I normally work in Java and PHP so although I understand the theory, I haven't worked with objects much in JavaScript before. Any help would be much appreciated! Similar TutorialsI'm writing a program that involves a network of interconnected nodes (or simply objects in my example below). It depends on being able to access properties of an object's linked objects (a bit oddly worded, sorry)... Problem is I'm not sure how to properly access those properties... see below please. <script> //This is an example of a problem im having in my own code... //I want to access the name of the object within the links array wintin the object... var objA = {name: "Object A", links: [objB, objC]}; var objB = {name: "Object B", links: [objC, objD, objE]}; var objC = {name: "Object C", links: [objB]}; var objD = {name: "Object D", links: [objE]}; var objE = {name: "Object E", links: [objD]}; //ex: I want to access the name of Object A's first link... console.log(objA.links[0].name); </script> I'm hoping to get "Object B"... But instead I get: TypeError: Result of expression 'objA.links[0]' [undefined] is not an object. Is there another way around this? Any thoughts are appreciated. So I'm pretty much new to JS, and I'm trying to write something, and I'm having a problem. It's a color picker. So I have an object that defines the default color, and then when the color is updated, the different css classes need to be updated as well. So here's what I was trying to do Code: var colorPicker = { mainColor: "red", backgroundColor: this.mainColor + "bkgd", } So problem 1 is I keep getting "undefined" returned for "this.mainColor". If I use colorPicker.mainColor, it hasn't been created yet so it throws an error. Problem two is if I update mainColor from another function, say to make mainColor = "green", then backgroundColor doesn't automatically update. Any help is appreciated. Thanks Hello everyone, I am fairly familiar with the concept of Objects and their properties and methods, but javascript being object based as opposed to object oriented has me stumped on how to access an object's properties from an onclick event handler created for another object created within the original object. In the example below, I have a constructor function called anyObj. to which I pass an object reference to an element. anyObj has 3 properties and one function increaseWidth() increaseWidth() creates a new button with an onclick event handler and this is where I have a problem. The onclick function needs to increase the value of anyObj's this.width property. I originally had a line this.width += 10; in the onclick but quickly realised why this wasn't working because the this in the onclick function refers to the new button object and not the this.width property of anyObj. The workaround I have used, and it works, is to make a copy of all the this.xxxxx properties. eg. width = this.width; and use the width variable in the onclick as you can see below. This "workaround" works fine but doesn't feel ideal to me. So, what I am asking advice on is, is there a better way to access the anyObj()'s properties from within the onclick function than the way I have done it? Obviously I would prefer to not have to make copies of all the anyObj() properties like I have to make them accessible to the onclick function. Code: function anyObj(divObj){ this.elem = divObj; this.width = 50; this.height = 50; this.increaseWidth=function(){ width = this.width; height = this.height; //create a button for this object to be appended to an element later on var newButton = document.createElement('button'); newButton.onclick=function(){ width += 10; //... //... } //... //... } } Hi, every time I try and alert: [ { number:0, secondnumber:0 }, { number:2, secondnumber:1 }, { number:1, secondnumber:2 } ] it just shows [object object], [object object], [object object]. Why is this and what can I do to make the record be shown as it is above in an alert? Thanks. I can't get any info from Firebug except that one line, uncaught exception [object Object]. The code fully worked, then I needed to make it dynamically create Sortables from the scriptaculous library based on how many X were in a table in my database, which I've done, and I'm thinking it may be a simple slight parse error of some type, I'm not too good with Javascript, because now my script barely works. I've double checked the script's source code, the PHP variables are exactly what they should be. Code: print<<<HERE Sortable.create('sortlist$box', { tag: 'img', overlap:'horizontal',constraint:false, containment: $list, dropOnEmpty: true, onChange: function(item) { var list = Sortable.options(item).element; if(changeEffect) changeEffect.cancel(); changeEffect = new Effect.Highlight('changeNotification', {restoreColor:"transparent" }); }, onDrop: function(item) { var thing=Sortable.options(item).element.identify(); var anchors = document.getElementById(thing).childNodes.length-2; if(anchors > 20){ alert('This box had 20 creatures in it already, your last action has not been saved.'); window.location.reload(); } else{ new Ajax.Request("saveImageOrder.php", { method: "post", parameters: { data: Sortable.serialize("sortlist$box") } }); } } }); HERE; $box++; } ?> }); </script> if you solve this I'll send ya $10 via paypal I created a method for displaying an object's properties: Code: renderfunction = false; function showProperty (object, property) { document.write ('<td class="type">' + (typeof object[property]) + '</td>' + '<td class="name">' + property + '</td>'); document.writeln('<td class="value">' + ( (typeof object[property] != 'function') ? object[property] :( (property != 'showProperties') ? ( renderfunction ? object[property]() : ('<span class="self">NOT RENDERED</span>') ) : ('<span class="self">THIS</span>') ) ) + '</td>'); document.writeln('<td class="hasOwnProperty" >' + ( object.hasOwnProperty(property) ? "Local" : "Inherited" ) + '</td>'); if (typeof object[property] == 'function') { document.writeln ('<td class="function">' + object[property] + '</td>'); } else { document.writeln ('<td class="function"> </td>'); } } As long as renderfunction = false, the object is fine coming out of this function. However, if I change renderfunction to true, all my properties become undefined. Why isn't this working as I expect it to? How should I fix it? Thanks in advance, -Brian. Hi all, I'm stumped on finding a way in javascript to create an object factory whose instances are also object factories. In short I want something like that below, but no joy ... any clues? Code: function createClass () { return new createClass() function createClass() { return new createInstance () function createInstance () { //Default properties, values and methods which might later be extended } } } var createDoor = createClass(); var door1 = createDoor(); var door2 = createDoor(); var createChair = createClass(); var chair1 = createChair (); var chair2 = createChair (); Ignore post (if mod, please delete)
Hello together! I generate html code with jsp. In that jsp there a several framesets and frames. And yes i know, frames are not really up to date but it's an old program and i have to deal with it now. Anyway, in the top frameset i have an onload attribute like onload="load()". In the function load i want to access the Element.prototype object. But unfortunately typeof Element gives me "undefined". So i looked a little deeper and found that window.toString() gives me "[object]" and not as expected "[object window]" so somehow my window doesn't know that its construcor is Window. window.construcor is "undefined" as well. And i don't have access to the Element object. I really don't know where the error could be. When the page is loaded and i access the same window over the console, then everything is right. But in my function a can't get access to the objects i need. I also don't know what part of the code could be useful to post here, but maybe someone had a similar problem before? i should say that this problem only occurs in IE8. In IE9 it works perfectly. Has anyone any idea?? Quote: menu: function( a, b ) { $( b ).observe( 'click', function( event ) { event.stop(); if( $( a ).visible() ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); } else { $( a ).show(); $( b ).addClassName( 'selected' ); document.observe( 'click', function( e ) { if( e.target.id != a && e.target.id != b && !Element.descendantOf( e.target, $( a ) ) ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); } }); } }); $$( '#' + b + ' > a' ).each( function( element ) { element.observe( 'click', function( event ) { $( a ).hide(); $( b ).removeClassName( 'selected' ); document.stopObserving( 'click' ); }); }); } This work's perfrect accept when i use it with others on the menu it leaves the other ones open, how do i get it to close the open one when i open a new menu.. Thanks. Hello. Is there any way to get the variable name of an object from inside the object? E.g. PHP Code: function Bla(){ this.write = function(){ document.write(<objectname>); } } obj1 = new Bla(); obj1.write(); //Outputs obj1 Here is my script: PHP Code: function myTimer(seconds, obj){ this.seconds = seconds; this.obj = obj; this.startTimer = function(){ if(this.seconds>0){ this.seconds--; this.obj.innerHTML = this.seconds; this.timer = setTimeout("Timer.start()",1000); } } } Timer = new Timer(10, obj); Timer.startTimer(); Now the problem is that the variable that contains the object must be named "Timer". This way I cannot create new timer objects with different variable names I have tried: this.timer = setTimeout("this.start()",1000); but it doesn't work. That's why it would be good to detect the variable name and instead use something like this: this.timer = setTimeout(varname+".start()",1000); I would rather not have to pass the variable name through a parameter like this: Timer1 = new Timer(10, obj, "Timer1"); Thanks in advance. hy all, I am creating an accordion menu that when i press the " UNIT " tab, it opens up a list of " Chapters " tab, and when i press on any one of those chapters, a list of lessons opens up. Till now, i have managed to create all the appropriate lists, but in default, lessons and chapters are opened automatically, and the lessons elements when pressed do not scroll back up to the chapters parents. My html5 file: Code: <script type="text/javascript" src="jqueryjs.js"></script> <script type="text/javascript" src="jqueryuiaccor.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#accordion').accordion(); }); </script> <div id="container"> <div id="content"> <div id="sidebar"> <ul id="accordion"> <li> <a href="#recent" class="heading">Unit 1</a> <ul id="accordion"> <li> <a href="#recent" class="heading">Chapter 1 </a> </li> <ul id="accordion2"> <li> Lesson 1 </li> </ul> </ul> </li> <li> <a href="#recent" class="heading">Unit 2</a> <ul id="accordion"> <li> <a href="#recent" class="heading">Chapter 1 </a> </li> <ul id="accordion"> <li> <a href="#recent" class="heading" role="tab" aria-expanded="true">Chapter 2 </a> <ul id="accordion"> <li> <a href="#recent" class="heading">Lesson 1 </a></li> </ul> </li> </ul> </ul> </li> </ul> </div> </div> </div> My acorjs.js file: Code: $(document).ready(function() { $('ul#accordion a.heading').click(function() { $(this).css('outline','none'); if($(this).parent().hasClass('current')) { $(this).siblings('ul').slideUp('slow',function() { $(this).parent().removeClass('current'); $.scrollTo('#accordion',1000); }); } else { $('ul#accordion li.current ul').slideUp('slow',function() { $(this).parent().removeClass('current'); }); $(this).siblings('ul').slideToggle('slow',function() { $(this).parent().toggleClass('current'); }); $.scrollTo('#accordion',1000); } return false; }); }); Please HELP! Hey is it possible to access javascript variables in an iframe src page from the parent page, or vice versa. How do you do this? What about the DOM? thanks i m trying to extract data from an xml file and display data on Google maps but when i try to run my code In IE - Access denied error is display (while accessing the xml file) Mozilla - code is working fine but displays following error - Error: xmlDoc.getElementsByTagName("lat")[1] is undefined Source File: file:///I:/BE%20Project%20Data/coding/Myexample/exam2.html Line: 48 HTML file- <html> <head> <title>Google Maps JavaScript API v3 Example: Fusion Tables Layer</title> <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" /> <style type="text/css"> html { height: 100% } body { height: 100%; margin: 0px; padding: 0px } #map_canvas { height: 500px;width: 800px } </style> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> <script type="text/javascript"> function initialize() { if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET","agridata.xml",false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; var latlng = new google.maps.LatLng(48.75028,-94.91667); var mapOpts = { zoom: 5, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP, }; var map = new google.maps.Map(document.getElementById("map_canvas"),mapOpts); var l1=xmlDoc.getElementsByTagName("lat")[1].childNodes[0].nodeValue; var l2=xmlDoc.getElementsByTagName("lng")[1].childNodes[0].nodeValue; var pt = new google.maps.LatLng(parseFloat(l1), parseFloat(l2)); var marker = new google.maps.Marker({ position: pt, map: map, title: 'Just a simple marker'}); } </script> </head> <body onload="initialize();"> <h1>output</h1> <div id="map_canvas"></div> </body> </html> XML file - <?xml version="1.0"?> <markers> <marker> <lat>52.09667</lat> <lng>-173.50056</lng> <state>Alaska</state> <county>Aleutian</county> </marker> <marker> <lat>48.75028</lat> <lng>-94.91667</lng> <state>Minnesota</state> <county>Lake of woods</county> </marker> <marker> <lat>52.09667</lat> <lng>-173.50056</lng> <state>Washington</state> <county>Stevans</county> </marker> </markers> do let me know the reason behind the undefined error and ACCESS DENIED error ... i have tried modification in the security setting of the browser but error is not solved yet ... thks Hello, I am working on a project using HTML and javascript to allow the user to choose a vehicle from a drop down menu, then load a new page showing some information about this vehicle. The information is stored in an Excel file. I posted regarding this issue a while back and got an excellent response from Old Pedant (thanks again!) about using ActiveX - which has thus far worked perfectly. My initial condition was that I would only be using IE7+. However, my next idea was to be able to use it on an IPad (which I unfortunately do not own yet, making any kind of testing difficult) which I am fairly certain ActiveX won't work on. So, I was looking for any other method which would be similar. Important note: this will not use the internet at all, all of these files will be available locally. There is a lot of material on running queries to servers, but I didn't think that would really apply here. It seems pretty clear that JS has difficulty accessing files client side (which I understand why completely), but I was hoping to find something that worked for the gray zone I'm currently working in since I'm not using servers at all. I know that this is not really the intended use of HTML/JS, but I was hoping that by writing it as an HTML file, it'd be accessible to anyone with a browser. Some of my target computers have odd limitations (such as not being to download .exe files). The code I based my original off of is shown below: Code: <script type="text/javascript"> var conn = new ActiveXObject("ADODB.Connection") conn.Open ( 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\full\path\to\MyExcel.xls;Extended Properties="Excel 8.0;HDR=Yes;IMEX=1";)'; var sql = "SELECT * FROM [nameOfSheet$]"; var rs = conn.execute( sql ) while ( ! rs.eof ) { // just an example of dumping everything from the sheet out to the browser: for ( var f = 0; f < rs.fields.count; ++f ) { document.write( rs.fields(f).value + "," ); } document.write("<br>\n"); rs.moveNext(); } rs.close(); conn.close(); </script><script type="text/javascript"> var conn = new ActiveXObject("ADODB.Connection") conn.Open ( 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\full\path\to\MyExcel.xls;Extended Properties="Excel 8.0;HDR=Yes;IMEX=1";)'; var sql = "SELECT * FROM [nameOfSheet$]"; var rs = conn.execute( sql ) while ( ! rs.eof ) { // just an example of dumping everything from the sheet out to the browser: for ( var f = 0; f < rs.fields.count; ++f ) { document.write( rs.fields(f).value + "," ); } document.write("<br>\n"); rs.moveNext(); } rs.close(); conn.close(); </script> Thank you, klarosa I have developped a script in order to resize the height of a div on a web page in order to display it at least up to the size of the window. Here is the code: function resize(){ var frame = document.getElementById("content"); var padding_top = parseInt(window.getComputedStyle(frame,null).getPropertyValue("padding-top")); var padding_bottom = parseInt(window.getComputedStyle(frame,null).getPropertyValue("padding-bottom")); var padding = padding_top + padding_bottom; var bodyheight = document.body.scrollHeight; var windowheight = window.innerHeight; if (bodyheight < windowheight){ frame.style.height = windowheight - padding + "px"; } } It works well, but I was wondering why I am not able to get the padding-top and -bottom using these two instructions: var padding_top = frame.style.paddingTop; var padding_bottom = frame.style.paddingBottom; The script runs but Firebug shows empty strings for both values. How come? Is there a bug in Firefox? Thanks inadvance for your time and help. I'm trying to accessing the Parent window fom a sub window previously opened using window.open I'm using firebug to t yand debug, and it shows that this DOM entry exists.. window.opener.location.href But trying to access it gives "window opener is null" error I've tried all these, and get the various errors tagged on the end... Code: <script language="JavaScript"> //alert(opener.location); // = opener is null //alert(opener.location.href); // = opener is null //alert(parent.location); // = uncaught exeption - could not convert to javascript argument arg 0 //alert(parent.location.href); // = Permission denied to get property Location.href //alert(parent.opener.location); // = uncaught exeption - could not convert to javascript argument arg 0 //alert(parent.opener.location.href); // = Permission denied to get property Location.href //alert(parent.window.opener.location.href); // = Permission denied to get property Location.href //alert(parent.window.opener.location.href); // = Permission denied to get property Location.href //alert(window.opener.location); // = window opener is null //alert(window.opener.location.href); // = window opener is null //alert(window.parent.location); // = uncaught exeption - could not convert to javascript argument arg 0 </script> driving me crazy! Anyone have a solution? What i have is a system where the amount of HTML lines is generated by php when the page loads. Each time has exactly the same set up except there names have an int added to them in accending order. What i need is for them to pass a variable to the javascript function telling them what number they are, and the javascript then using this to access it to read and change information. Is the line below correct for this task? Code: document.Purchase.(Tax+i).selectedIndex; Hello, I have a simple form with simple validation. I am just playing around a bit with forms and don't really have concrete knowledge. What I have done is created a form. Asking for first name, last name, age and email. When the user clicks the submit button I want 2 functions to run, the first checking the input is correct and also making sure all fields have a value. Once everything is checked and is O.K I want to go into another function which sends all this information to an array one by one. I am having difficulty accessing each individual input tag. I could achieve what I want to do, but it will take double the lines of code because each input has a different 'name'. So, what I am trying to do is access the input tags the same as you would do an array. Here is my code: HTML: Code: <form name="regForm" id="form"> <fieldset> <legend>Real Heroes - Registration Form</legend> <p>First Name:<input type="text" size="30" maxlength="20" name="txtFirstName" /></p> <p>Last Name:<input type="text" size="30" maxlength="20" name="txtLastName" /></p> <p>Age:<input type="text" size="30" maxlength="3" name="txtAge" /></p> <p>Email Address:<input type="text" size="30" maxlength="50" name="email" /></p> <p><input type="button" value="Submit Registration" name="butChkForm" onclick="callFuncs_onclick()" /> <input type="reset" value="Reset" name="resetForm" /></p> </fieldset> </form> JavaScript: Code: //CALLING THE FORM SCRIPTS// function callFuncs_onclick() { chkForm_onclick(); creatingDatabase_onclick(); } //**************FORM VALIDATION***************// function chkForm_onclick() { var theForm = document.regForm; if (theForm.txtFirstName.value == "" || theForm.txtLastName.value == "" || theForm.txtAge.value == "" || theForm.email.value == "") { alert("Please complete all of the form."); if (theForm.txtFirstName.value == "") { theForm.txtFirstName.focus(); } if (theForm.txtLastName.value == "") { theForm.txtLastName.focus(); } if (theForm.txtAge.value == "") { theForm.txtAge.focus(); } if (theForm.email.value == "") { theForm.email.focus(); } } else if (isNaN(theForm.txtAge.value)) { alert("That is not valid input for this field. Please re-enter your age."); theForm.txtAge.focus(); } else { alert("Thank you for completing the form, " + theForm.txtFirstName.value); } } function creatingDatabase_onclick() { var form = document.regForm; var index = form.input[0].value; alert(index); } I'm not quite sure where I am going wrong. Please note that these functions really labour the point, I know I have way too many lines of code but I am still very amateur with JS. Thank you for any help/information. Kind Regards, LC. i have this code: PHP Code: <?php foreach ($freechat_list as $r) { $uniqueCode = substr($r,0,12); $id = substr($r,13); $blocked_record = RcBlockListTablePeer::isBlocked($id,$requestor_id); ?> <a href="#" id="profilelink" name="profilelink" onClick="return viewornot(<?php echo $id."/".$blocked_record; ?>)"><?php echo $uniqueCode; ?></a> } then i have my JS: [CODE] thank you all but i am totally confused now...here is my full code: <?php foreach ($freechat_list as $r) { $uniqueCode = substr($r,0,12); $id = substr($r,13); $blocked_record = RcBlockListTablePeer::isBlocked($id,$requestor_id); ?> <a href="#" id="profilelink" name="profilelink" onClick="return viewornot(<?php echo $id."/".$blocked_record; ?>)"><?php echo $uniqueCode; ?></a> } my JS: Code: function viewornot(id) { alert(id); } alert(id) only gives me the id but in my href i concatenated it with blocked_record: viewornot(<?php echo $id."/".$blocked_record; ?>) please help? |