0

I have a javascript object which I want to access by a dynamic variable:

var color = {
                red : '#ff0000',
                black : '#000000',
                silver : '#7d8989'
            };

var currentColor = $(val).html();

console.log(color[currentColor]);

But I get undefined message by the console. How can I access the data?

EDIT:

Problem was that the option value had whitespace at its end, thanks everyone for fast reply:

var currentColor = $.trim($(val).html());
ThreeCheeseHigh
  • 1,363
  • 5
  • 21
  • 40

6 Answers6

2

This works. Like the comment, I'm not sure what "val" is, but if it's an ID, make sure it's targeted correctly.

HTML:

<p id="val">red</p>

JS:

var color = {
                red : '#ff0000',
                black : '#000000',
                silver : '#7d8989'
            };
var currentColor = $("#val").html();
console.log(color[currentColor]);
Anthony Hessler
  • 1,461
  • 1
  • 11
  • 10
  • @blachawk Dot notation isn't possible with a dynamic value. There is no `currentColor` property of `color` - you have to use bracket notation like they have it – Ian May 10 '13 at 14:07
0

You maybe want to trim your string before finding the color in your map:

var color = {
    red : '#ff0000',
    black : '#000000',
    silver : '#7d8989'
};

var currentColor = $.trim( $(val).html() );

console.log(color[currentColor]);

And it's not very fast to route your data through the DOMNodes like that.

Andreas Louv
  • 44,338
  • 13
  • 91
  • 116
0

Your code seems to be working fine, so it is probably something wrong with your selector See http://jsfiddle.net/9GPbv/1/ works fine

<div class="val">red</div>

var color = {
                red : '#ff0000',
                black : '#000000',
                silver : '#7d8989'
            };

var currentColor = $(".val").html();

alert(color[currentColor]);

Also if your using an input like at http://jsfiddle.net/tMFZr/ you should use .val() not .html()

Dominic Green
  • 10,024
  • 4
  • 28
  • 34
0

You should use quotes in your object since you will be using it as string values: HTML

<div id="val">red</div>

JS

var color = {
                'red' : '#ff0000',
                'black' : '#000000',
                'silver' : '#7d8989'
            };

var currentColor = $(val).html();

console.log(color[currentColor]);
rafaelcastrocouto
  • 11,128
  • 2
  • 37
  • 60
0

I think you are getting the undefined in the chrome console. IF so please take a look at What does it mean if console.log(4) outputs undefined in Chrome Console?

Community
  • 1
  • 1
NT88
  • 947
  • 5
  • 25
0

If your html have an id:

var color = {
    red : '#ff0000',
    black : '#000000',
    silver : '#7d8989'
};
var currentColor = document.getElementById("val").innerText;
console.log(currentColor);
console.log(color[currentColor]);
lfergon
  • 963
  • 14
  • 27