Simple syntax issue on variables

Discussion in 'JavaScript' started by Submerged, Jul 27, 2009.

  1. #1
    Hey, this should be a piece of cake for Javascipt coders. I'm a PHP guy myself :) Basically, I'm trying to use variables in a document.form.field.value call. The two variables are 'currentadset' and 'currentadloc', both of which have integer values.
    setadlocs[currentadset][currentadloc] = document.setadlocations2.ad{currentadset}loc{currentadloc}.value;
    Code (markup):
    Thanks for the help!
     
    Last edited: Jul 27, 2009
    Submerged, Jul 27, 2009 IP
  2. dimitar christoff

    dimitar christoff Active Member

    Messages:
    882
    Likes Received:
    62
    Best Answers:
    0
    Trophy Points:
    90
    #2
    setting up and accessing multidimensional arrays with dynamic keys can be a bit touch-and-go in javascript... you need to start thinking of lego blocks that you glue together :)
    var currentadset = 4, currentadloc = 2; // whatever they are
    var sub = [], setadlocs = []; // create empty arrays
    // now assign them.
    sub[currentadloc] = "foo"; // set the value of the second array (read below how to read this from an element's value)
    setadlocs[currentadset] = sub; // adopt the array
    
    // to use console, install firebug from www.getfirebug.com (for firefox). else, replace with alert()
    console.log(setadlocs); // the whole thing with the undefined keys, this wont work on alert
    console.log(setadlocs[4][2]); // outputs 'foo'
    console.log(setadlocs[currentadset][currentadloc]); // outputs 'foo' also.
    
    // static representation of this object would be:
    var foo = {4: {2: "foo"}};
    
    PHP:
    unfortunately, as the keys are dynamic and cannot be used like this:
    var foo = {currentadloc: "foo"}; // it won't evaluate the value of currentadloc but use the string instead.
    ... you need to be more creative and treat the object as an array :)

    i hope this makes sense.

    p.s. document.setadlocations2.ad{currentadset}loc{currentadloc}.value; -> bad form. you may need to give the field an id, then use:

    document.getElementById("ad" + currentadset + "loc" + currentadloc).getAttribute("value") (or .value) instead.
     
    Last edited: Jul 28, 2009
    dimitar christoff, Jul 27, 2009 IP
    Submerged likes this.
  3. Submerged

    Submerged Active Member

    Messages:
    132
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    51
    #3
    Awesome! You had an extra " at the end of currentadloc with the last code there, but no big deal -- consider yourself repped :)
     
    Submerged, Jul 28, 2009 IP