0

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.

0

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

hi Axel, i still get the same result. if i alert nameList.name_out, i get undefined. If I alert nameList.rom then I get the value. It would appear that the name_out value is incorrectly formatted.
Can you post the HTML you're attempting to retrieve these values from?
I've updated my answer with the solution. I believe you're just referencing your array incorrectly.
1

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

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.