I created a simple html that enumerates names, with people's names on it as classes. I then get the class name and check it against the array. the result is undefined. here's my code:
var prof_name = $(this).attr('class');
var n = prof_name.split(' ');
var name_out = n[0];
var nameList = {'rom':'Rommel Santiago','holy':'Holiander Fields'};
var nameValue = nameList.nameout;
alert(nameValue); //this pops up as undefined
alert(nameList.rom) // this pops up as 'Rommel Santiago'
What did i missed?
thanks.
3 Answers 3
The issue is you're referencing your array incorrectly. I'm assuming your class name for $(this) is rom holy
You're retrieving rom like this: var name_out = n[0];
And you want to reference the rom key in nameList, which you can like this:
var nameValue = nameList[name_out];
After doing this, your updated code will look like this:
var prof_name = $(this).attr('class');
var n = prof_name.split(' ');
var name_out = n[0];
var nameList = {'rom':'Rommel Santiago','holy':'Holiander Fields'};
var nameValue = nameList[name_out];
alert(nameValue); //this pops up as Rommel Santiago
Working Example: http://jsfiddle.net/6GM7T/2/
Furthermore
I'd advise you to not use classes for storing data.
You can use the data attribute tag instead, like this:
<div id="myDiv" data-name="Rommel Santiago"></div>
And you can easily retrieve that data with jQuery using this:
$('#myDiv').data('name'); //returns Rommel Santiago
3 Comments
I believe the OP wants to use the value of name_out as the index to nameList, in which case:
var nameValue = nameList.nameout;
should be:
var nameValue = nameList[name_out];
Comments
As they said
It works with this
var prof_name = "rom holy";
var n = prof_name.split(' ');
var name_out = n[0];
alert("Parameter Selected = "+name_out);
var nameList = {'rom':'Rommel Santiago','holy':'Holiander Fields'};
var nameValue = nameList[name_out];
alert("From Object : "+nameValue); //this pops up as undefined
alert("Actual Value = "+nameList.rom) // this pops up as 'Rommel Santiago'
http://jsfiddle.net/Kartheek/nx3WQ/1/
if you call like nameList.nameout it actually searching for nameout as a parameter in namelist
if u use nameList[nameout] it searches for index nameout value.