JavaScript - Funky Object Issues
So I'm re-writing my procedural Back Jack program to be Object Oriented so that I can add a split option and some other features and I've run into this weird bug...
This is the beginning of the function that assembles the HTML for each card when it is added. hand.prototype.createCardsHTML = function (cardNum) { console.log(this.cards); console.log(this.cards[cardNum]); console.log(this.cards[cardNum].name); if(this.player == "dealer" && cardNum == 0){ this.cards[cardNum].imgHTML = '<img src="images/cards/b2fv.png" alt="dealer pocket" />'; } else{ this.cards[cardNum].imgHTML = '<img src="images/cards/' + this.cards[cardNum].image +'" alt="' + this.cards[cardNum].name + ' of ' + this.cards[cardNum].suit +'s" />'; } attached is a screen shot of the console.log reports, as you can see the object get stored in the array but for whatever reason I can't access it's individual properties. This only occurs when the hit function is called, not when the initial hands are generated. I'm really confused so any help is appreciated. Also here is the entire script (note: it's very long, a bit disorganized and not yet complete) // JavaScript Document // JavaScript Document window.onload = blackJackTable; function blackJackTable () { //set-ables var insCost = 50; var dlrHitsOn = 17; var minBet = 10; var bank = 500; //Utilities var usedCards = new Array(53); var roundOver = true; var allBetsPlaced = false; var dealerWent = false; //var dlrIncrement = 0; //var plrIncrement = 0; //Load Objects loadJSON("data.json"); function loadJSON(url) { var headID = document.getElementsByTagName("head")[0]; var newScript = document.createElement('script'); newScript.type = 'text/javascript'; newScript.src = url; headID.appendChild(newScript); newScript.onreadystatechange= function () { if (this.readyState == 'complete' || this.readyState == 'loaded') startGame(); } newScript.onload= startGame; } function startGame() { //console.log(deck); //construct players function player(playerIdent){ this.lastBet = 0; this.bet = 0; this.playerName = playerIdent; this.hands = new Array(); this.betPlaced = false; this.bank = bank; this.insured = false; } //Construct Hands function hand(playerName, id, bet) { this.total = 0; this.locked = false; this.over = true; this.player = playerName; this.id = id; this.bet = bet; this.aces = 0; this.handDiv = new Array(); this.cards = this.newCard(2); // adds to cards at random to hand, updates aces and total } //function for adding cards to a hand hand.prototype.newCard = function (howMany){ var cards = new Array(); for(i=0; i<howMany; i++){ var card; do { card = Math.floor(Math.random() * 52); } //Check to see if the card is in use while (usedCards[card]); //Add card to used array usedCards[card] = true; var nextCard = cards.length; cards[nextCard] = deck[card]; //check for ace if(cards[nextCard].value == 11){ this.aces += 1; //check for dealer ace in second slot if(this.player == "dealer" && cards.length == 2){ //call offer insurance if dealer has ace in second slot this.offerIns();///!!! re-write to reference hand not player } } this.total += cards[nextCard].value; } //update player total return cards; } //DOM commands to generate dealer area HTML player.prototype.generateDlrHTML = function () { this.dlrRegion = document.getElementById('dealer-region'); //creates a div for dealer hand this.plrHands = document.createElement('div'); //sets the class name for dealer hand div this.plrHands.setAttribute('class', 'dealer-hands'); //adds dealerhand div to dlrRegion div this.dlrRegion.appendChild(this.plrHands); //creates a div for dealer total this.dealerTotalRegion = document.createElement('div'); //sets the class name for dealer hand div this.dealerTotalRegion.setAttribute('class', 'dealer-total'); //adds dealertotal div to dlrRegion div this.plrHands.appendChild(this.dealerTotalRegion); } //DOM commands to generate each player area HTML player.prototype.generatePlrHTML = function () { this.plrRegion = document.getElementById('players-region'); //creates a div for player hands this.plrHands = document.createElement('div'); //sets the class name for player hands div and adds it to region this.plrHands.setAttribute('class', 'hands'); this.plrRegion.appendChild(this.plrHands); //Create player bet and bank region this.hud = document.createElement('div'); //sets the class name for player hud and adds to region this.hud.setAttribute('class', 'hud'); this.plrRegion.appendChild(this.hud); //Create bank display this.bankDisplay = document.createElement('span'); //sets the class name for player hud and adds to region this.bankDisplay.setAttribute('class', 'bank-display'); this.hud.appendChild(this.bankDisplay); //Create bet display this.betDisplay = document.createElement('span'); //sets the class name for player hud and adds to region this.betDisplay.setAttribute('class', 'bet-display'); this.hud.appendChild(this.betDisplay); //Create bet field this.betField = document.createElement('input'); //sets the class name for player hud and adds to region this.betField .setAttribute('class', 'bet-input'); this.betField .setAttribute('type', 'text'); this.betField .setAttribute('value', 'bet here'); this.betField .setAttribute('name', 'bet-input'); this.hud.appendChild(this.betField ); //Create bet Button this.betBtn = document.createElement('input'); //sets the class name for player hud and adds to region this.betBtn.setAttribute('class', 'bet-btn'); this.betBtn.setAttribute('type', 'button'); this.betBtn.setAttribute('value', 'Bet'); this.betBtn.setAttribute('name', 'Bet'); this.hud.appendChild(this.betBtn); var subvertEvent = this; this.betBtn.onclick = function () { subvertEvent.placeBet();}; //Create deal button this.dealBtn = document.createElement('input'); //sets the class name for player hud and adds to region this.dealBtn.setAttribute('class', 'deal-btn'); this.dealBtn.setAttribute('type', 'button'); this.dealBtn.setAttribute('value', 'Deal'); this.dealBtn.setAttribute('name', 'Deal'); this.hud.appendChild(this.dealBtn); this.dealBtn.onclick = function () { subvertEvent.deal();}; } //DOM commands to create hand HTML player.prototype.createHandHTML = function (handNum){ //for(i=0; i<this.hands.length; i++){ //Create a hand div this.hands[handNum].handDiv = document.createElement('div'); //sets the class name for player hud and adds to region var handClass = 'hand-' +this.hands[handNum].id; this.hands[handNum].handDiv.setAttribute('class', handClass); this.plrHands.appendChild(this.hands[handNum].handDiv); this.hands[handNum].createHandCtrlHTML(handNum); //} } //Hit - adds and displays card to hand hand.prototype.hit = function () { this.cards.push(this.newCard(1)); var cardNum = this.cards.length -1; this.createCardsHTML(cardNum); } //Stand - Locks hand - If all hands are locked triggers dealersTurn() hand.prototype.stand = function () { //lock this hand this.locked = true; if(checkAllLocked == true){ dealersTurn(); } } //Double Down - doubles bet on hand calls hit for a single card then forces a stand. hand.prototype.doubleDown = function () { if (this.total > 0 && this.cards.length == 2){ //double bet this.bet = this.bet * 2; //!!!update bet //draw a card this.hit(); //force player to stand this.stand(); } else{ var message = "Sir/Maddam you cannot double down at this time."; dealerSays(message, "okay"); } } //Split - Creates a new player hand and assigns a new bet, moves cards as appropriate. hand.prototype.splitHand = function () { } //Creates hand control HTML hand.prototype.createHandCtrlHTML = function (handNum) { if(this.player != "dealer"){ //hand Control Region this.handControl = document.createElement('div'); //sets the class name for player hud and adds to region this.handControl.setAttribute('class', 'hand-control'); this.handDiv.appendChild(this.handControl); //Create hit button this.hitBtn = document.createElement('input'); //sets the class name for player hud and adds to region this.hitBtn.setAttribute('class', 'hit-btn'); var btnId = 'hit-btn-' + this.player + '-' + this.id; this.hitBtn.setAttribute('id', 'btnId'); this.hitBtn.setAttribute('type', 'button'); this.hitBtn.setAttribute('value', 'Hit'); this.hitBtn.setAttribute('name', 'Hit'); this.handControl.appendChild(this.hitBtn); var subvertEvent = this; this.hitBtn.onclick = function () { subvertEvent.hit();}; //Create Stand button this.standBtn = document.createElement('input'); //sets the class name for player hud and adds to region this.standBtn.setAttribute('class', 'hit-btn'); var btnId = 'stand-btn-' + this.player + '-' + this.id; this.standBtn.setAttribute('id', 'btnId'); this.standBtn.setAttribute('type', 'button'); this.standBtn.setAttribute('value', 'Stand'); this.standBtn.setAttribute('name', 'Stand'); this.handControl.appendChild(this.standBtn); this.standBtn.onclick = function () { hands[handNum].stand();}; //Create Double Down button this.dDBtn = document.createElement('input'); //sets the class name for player hud and adds to region this.dDBtn.setAttribute('class', 'hit-btn'); var btnId = 'doubledown-btn-' + this.player + '-' + this.id; this.dDBtn.setAttribute('id', 'btnId'); this.dDBtn.setAttribute('type', 'button'); this.dDBtn.setAttribute('value', 'Double Down'); this.dDBtn.setAttribute('name', 'Double Down'); this.handControl.appendChild(this.dDBtn); this.dDBtn.onclick = function () { hands[handNum].doubleDown();}; //Create Split button this.splitBtn = document.createElement('input'); //sets the class name for player hud and adds to region this.splitBtn.setAttribute('class', 'hit-btn'); var btnId = 'split-btn-' + this.player + '-' + this.id; this.splitBtn.setAttribute('id', 'btnId'); this.splitBtn.setAttribute('type', 'button'); this.splitBtn.setAttribute('value', 'Double Down'); this.splitBtn.setAttribute('name', 'Double Down'); this.handControl.appendChild(this.splitBtn); this.splitBtn.onclick = function () { hands[handNum].splitHand();}; } } //Actived when used hits "deal" button - Adds a hand object to player object if appropriate //!!!Does not support multiplayer by design player.prototype.deal = function () { if(allBetsPlaced == true && roundOver == true){ //wipes old hands clearHands(); //adds a new hand players[0].newHand(); this.newHand(); //sets round over to false as this begins the new round roundOver = false; } } //New hand function creates a new hand called by deal and split player.prototype.newHand = function () { var handIdPass = this.hands.length + 1; this.hands.push(new hand(this.playerName, handIdPass, this.bet)); var handNum = this.hands.length - 1; //alert(this.hands.length); this.createHandHTML(handNum); for (i=0; i<this.hands[handNum].cards.length; i++){ this.hands[handNum].createCardsHTML(i); } } //DOM commands to create cards hand.prototype.createCardsHTML = function (cardNum) { console.log(this.cards); console.log(this.cards[cardNum]); console.log(this.cards[cardNum].name); if(this.player == "dealer" && cardNum == 0){ this.cards[cardNum].imgHTML = '<img src="images/cards/b2fv.png" alt="dealer pocket" />'; } else{ this.cards[cardNum].imgHTML = '<img src="images/cards/' + this.cards[cardNum].image +'" alt="' + this.cards[cardNum].name + ' of ' + this.cards[cardNum].suit +'s" />'; } this.cards[cardNum].cardDiv = document.createElement('div'); var cardId = 'card-' + this.cards[cardNum].id; this.cards[cardNum].cardDiv.setAttribute('id', cardId); $(this.cards[cardNum].cardDiv).hide(); this.cards[cardNum].cardDiv.innerHTML = this.cards[cardNum].imgHTML; this.handDiv.appendChild(this.cards[cardNum].cardDiv); $(this.cards[cardNum].cardDiv).fadeIn(1000); } ..... Similar TutorialsHey guys, First post i have searched the web a lot on this subject and am still confused so i thought id try and get some help from the experts, the following function works great in every browser except IE, the line of code that breaks in IE is highlighted in red. I have read some topics about this not working in IE and saw some workarounds with innerhtml or something but i don't really understand. Can someone please take some time to figure out a fix for this? Code: function displayStream(live_id) { var stream_out = document.getElementById("stream_out"); for (var j = 0; j < stream_out.childNodes.length; j++) { stream_out.removeChild(stream_out.childNodes[j]); } var object = document.createElement("object"); object.setAttribute("height", "475"); object.setAttribute("width", "998"); var param = document.createElement("param"); //param.setAttribute("name", "movie"); param.name = 'movie'; param.setAttribute("value", "http://www.own3d.tv/livestream/" + live_id); object.appendChild(param); var param = document.createElement("param"); param.setAttribute("name", "allowfullscreen"); param.setAttribute("value", "true"); object.appendChild(param); var param = document.createElement("param"); //param.setAttribute("name", "wmode"); param.name = 'wmode'; param.setAttribute("value", "transparent"); object.appendChild(param); var embed = document.createElement('embed'); embed.setAttribute("type", "application/x-shockwave-flash"); embed.setAttribute("src", "http://www.own3d.tv/livestream/" + live_id +";autoplay=true"); embed.setAttribute("allowfullscreen", "true"); embed.setAttribute("wmode", "transparent"); embed.setAttribute("height", "475"); embed.setAttribute("width", "998"); object.appendChild(embed); stream_out.appendChild(object); } Hi there. I have a table which I would like to be highlighted with the click of a button, but I can't seem to reference it correctly. I can make the <td> clickable and function, but when I try to apply it to the button I can't make it reference the td cell, rather than change the background color of the button. The function is: function roll(obj){ obj.style.backgroundColor == "pink" ? obj.style.backgroundColor = "#e5e5e5" : obj.style.backgroundColor = "pink"; } Html: <td style="background-color:#e5e5e5;"><img onmousedown="roll(this);" src="images/plus.png" title="Highlight Lot" /></td> Thanks a lot!! :) I am building a website for a client. This will involve some tricky form work. There will be forms on 2 pages. The first will be of generic questions such as: "How many windows in you household?" After these questions are answered, a "Continue" button would be pressed. Then "Do you want your windows cleaned?" would be an option on the second page. At the end of that form on the second page, it would calculate the true answers with the filled in info from the first page. This is the way the client wants it. How would I go about this? I've been looking for ways to get seperate forms to cooperate with each other, I'd assume with ID tags and such, but can't find any good help. Any insight would be great!! 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 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. 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 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?? I'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. 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 (); 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. I am trying to troubleshoot my javascript function below. Code: <script type="text/javascript"> function txtboxfill(fillobj) { var rChar=String.fromCharCode(13); var myVal = "To: " + this.form.to.value + rChar; myVal = myVal + "From: " + this.form.from.value + rChar; myVal = myVal + "Subj: " + this.form.subj.value + rChar + rChar; myVal = myVal + "Message: "; fillobj.value = myVal; } </script> Then I have a text box input field with an Code: <input type="text" id="tp" name="to" size="34" class="totext" onkeyup="txtboxfill(this.form.msg_area);"> and when I enter text in this field it gives me a 'this.form.to' is null or not an object and does not populate the textarea. BTW, msg_area is the id of my textarea. Thank you. Code: function globals() { this.states = ""; } now I can: Code: globals.states = .... how to extend first code to be able: Code: globals.states.something = .... ? Hi All, (Another Post LOL) Ive been getting alot of help with js recently THANKS! One last thing and i shouldnt be on here for a while How would i go about doing this Code: <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="750" height="550" codebase="http://active.macromedia.com/flash4/cabs/swflash.cab#version=4,0,0,0"> <param name="movie" value="SWF/helicopter.swf"> <param name="quality" value="high"> <param name="menu" value="false"> </object> into JS using .innerHTML = "Above Stuff"; I always get an error + i dont know how im going wrong with the quotes :S ANY HELP (GOOD STUFF); Thanks In Advance, Jamie. NOM NOM NOM! Hello, below you will find two objects, background and photo1, which I need help cleaning up a bit. This will eventually be imported using Json but for now during development it sits as is in my script. I need help with a couple things: - You will notice the 'val' property is identical in both objects. How can I move this into an outside function that each object can share? I'm having trouble bc I couldn't get 'this' to work outside of its current context. - Second, how can I restructure this so that I can instantiate a new object. So if I wanted to add a new layer I'd like to do something like importLayers.push[new Layer('photo2')] Code: var importLayers = { background: { layerType: 'background', index: 0, layerContent: { content: function() { return $(element).find('#background_Content'); }, width: 850, height: 530, xPos: 0, yPos: -150, skewX: 0, skewY: 0, angle: 0, originX: function() { return (this.sWidth() / 2); }, originY: function() { return (this.sHeight() / 2); }, scaleX: 1, scaleY: 1, sWidth: function() { return this.width * this.scaleX; }, sHeight: function() { return this.height * this.scaleY; }, aspect: 0, opacity: 100, val: function(prop, val) { switch(prop) { case 'width': if(plugin.constrain) this.scaleX = this.scaleY = val / this.width; else this.scaleX = val / this.width; break; case 'height': if(plugin.constrain) this.scaleY = this.scaleX = val / this.height; else this.scaleY = val / this.height; break; case 'angle': this.angle = val; } buildTransformation(this, this.content()); } }, }, photo1: { layerType: 'photo', index: 1, layerContent: { content: function() { return $(element).find('#photo1_Content'); }, width: 1920, height: 1280, xPos: 0, yPos: 0, skewX: 0, skewY: 0, angle: 0, originX: function() { return (this.sWidth() / 2); }, originY: function() { return (this.sHeight() / 2); }, scaleX: .15625, scaleY: .15625, sWidth: function() { return this.width * this.scaleX; }, sHeight: function() { return this.height * this.scaleY; }, aspect: 0, opacity: 100, val: function(prop, val) { switch(prop) { case 'width': if(plugin.constrain) this.scaleX = this.scaleY = val / this.width; else this.scaleX = val / this.width; break; case 'height': if(plugin.constrain) this.scaleY = this.scaleX = val / this.height; else this.scaleY = val / this.height; break; case 'angle': this.angle = val; } buildTransformation(this, this.content()); } }, } } Greetings, I have a floating object that work find within my page. However, I would like to only show after a button is clicked. Any ideas how to do this. Thanks I just really needed to know something about the whitespace between nodes in a tree structure. I know that Firefox's, Safari's, Chrome's and Opera's DOM treat the whitespace as a node. I am wondering what nodeType whitespace would return? Thank you all for any help + sugestions. I've been working through a tutorial on OOP in javascript. Upon keyup, the code below gives this error: Quote: charCounterObj[x] is undefined This is my first attempt at anything like this, so apologies for what are no doubt egregious and fundamental misunderstnadings about how to implement something like this. I've stripped away everything that's irrelevant, but there's still quite a bit of code here. I'm hoping this isn't too much wade through, but perhaps someone would be kind enough to give it the once-over. There may be something obvious that jumps out to the seasoned eye... Code: //CharCounter Class function charCounterClass(formType) { //Properties this.counter = $('#'+formType+'_commentsCounter'); this.textarea = $('#'+formType+'_comment'); this.maxlength = $('#'+formType+'_commentMaxlength').text(); this.textLen = this.textarea.val().length; //Methods this.cch = function() { $(this.counter).val(this.textLen); //... } } var charCounterObj = []; var charCounter = []; var x = 0; $("input.charCounter").each(function() { charCounter[x] = $(this).val(); if (charCounter[x] == true) { charCounterObj[x] = new charCounterClass(formType[x]); $('#'+formType[x]+'_comment').keyup(function() { charCounterObj[x].cch(); }); } x++; }); Thanks for any input. 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! |