Nishant Kumar
Nishant Kumar

Reputation: 6093

How to retrieve value from object in JavaScript

Hi I am using a Java script variable

var parameter = $(this).find('#[id$=hfUrl]').val();

This value return to parameter now

"{'objType':'100','objID':'226','prevVoting':'"   // THIS VALUE RETURN BY 

$(this).find('[$id=hfurl]').val();

I want to store objType value in new:

 var OBJECTTYPE = //WHAT SHOULD I WRITE so OBJECTTYPE contain 400

I am trying

OBJECTTYPE = parameter.objType; // but it's not working...

What should I do?

Upvotes: 1

Views: 386

Answers (2)

Felix Kling
Felix Kling

Reputation: 817148

Ok, not sure if I am correct but lets see:

You say you are storing {'objType':'100','objID':'226','prevVoting':' as string in a hidden field. The string is not a correct JSON string. It should look like this:

{"objType":100,"objID":226,"prevVoting":""}

You have to use double-quotes for strings inside a JSON object. For more information, see http://json.org/

Now, I think with $(this).find('[$id=hfurl]'); you want to retrieve that value. It looks like you are trying to find an element with ID hfurl,but $id is not a valid HTML attribute. This seems like very wrong jQuery to me. Try this instead:

var parameter = $('#hfurl').val();

parameter will contain a JSON string, so you have to parse it before you can access the values:

parameter = $.parseJSON(parameter);

Then you should be able to access the data with parameter.objType.

Update:

I would not store "broken" JSON in the field. Store the string similar to the one I shoed above and if you want to add values you can do it after parsing like so:

parameter.vote = vote;
parameter.myvote = vote;

It is less error prone.

Upvotes: 1

abahgat
abahgat

Reputation: 13530

Try using parameter['objType'].

Just a note: your code snippet doesn't look right, but I guess you just posted it wrong.

Upvotes: 1

Related Questions