netdjw
netdjw

Reputation: 6007

How to access object using jQuery and HTML select element?

I have this structure:

var data = {
    'horizontal':{
         'static':[1,3,5,7,9],
         'dynamic':[2,4,6,8]
    },
    'vertical':{
         'static':[1,3,5,7,9],
         'dynamic':[2,4,6,8]
    }
};

I have this HTML objects:

Direction:
<select id="direction">
    <option value="horizontal">Horizontal</option>
    <option value="vertictal">Vertictal</option>
</select>

Type:
<select id="mytype">
    <option value="static">Static</option>
    <option value="dynamic">Dynamic</option>
</select>

Can I access to the data.horizontal.static[2] somehow like this?

var result = data.[ $('#direction').val() ].[ $('#mytype').val() ][2];

Is there any way?

Upvotes: 2

Views: 1596

Answers (3)

Vladimir Cherepinskiy
Vladimir Cherepinskiy

Reputation: 337

try remove dots

var result = data[ $('#direction').val() ][ $('#mytype').val() ][2];

Upvotes: 1

Chris Dixon
Chris Dixon

Reputation: 9167

Not sure what value you're wanting here, but this is how you access your values:

console.log(data['horizontal']);
console.log(data['horizontal']['static']);
console.log(data['horizontal']['static'][2]);

Fiddle:

http://jsfiddle.net/jj49G/

Upvotes: 0

BLSully
BLSully

Reputation: 5929

Your syntax is close.... you need:

var result = data[ $('#direction').val() ][ $('#mytype').val() ][2];

Note (no periods between square brackets)

Upvotes: 1

Related Questions