Skip to main content
  1. About
  2. For Teams
Asked
Viewed 41 times
0

I am trying to dynamically change the options available to a user. A user will choose either 1 or 2. Once they choose a value, I need to load the options associated with that value. Currently, i have the following:

var json = {'1':[{ 'value':'A', 'text':'Option - A'}, { 'value':'B', 'text':'Option - B'}], '2':[{ 'value':'A', 'text':'Choice - A'}, { 'value':'B', 'text':'Choice - B'}]};

var userWants = '1';
alert(json[userWants]);

Oddly, the alert window just displays ,. I don't understand why. What am I doing wrong?

1

3 Answers 3

1

Alerts cannot display JSON objects in their natural form. Try logging instead

var json = {'1':[{ 'value':'A', 'text':'Option - A'}, { 'value':'B', 'text':'Option - B'}], '2':[{ 'value':'A', 'text':'Choice - A'}, { 'value':'B', 'text':'Choice - B'}]};

var userWants = '1';
console.log(json[userWants]);

Also, see how to alert javascript object

Sign up to request clarification or add additional context in comments.

7 Comments

I see the same thing in the console window that I see in my alert window.
@user70192, what about using the snippet from my answer?
The snippet works fine. But not in my actual code. I don't understand why.
@user70192, can you replicate it in a fiddle so I can try and diagnose?
The problem is that json is actually a string value in my code. So, I'm now using JSON.parse. However, I'm now getting "Uncaught SyntaxError: Unexpected token '"
|
1

Alert converts the object to a string using .toString(), which doesn't give you nice output:

var a = {'value': 'A', 'text': 'Option - A'};
alert(a); // should alert [object Object]

You can use JSON.stringify to display the object nicely:

alert(JSON.stringify(a)); // should alert {"value":"A","text":"Option - A"}

Or:

var json = {'1':[{ 'value':'A', 'text':'Option - A'}, { 'value':'B', 'text':'Option - B'}], '2':[{ 'value':'A', 'text':'Choice - A'}, { 'value':'B', 'text':'Choice - B'}]};
var userWants = '1';
alert(JSON.stringify(json[userWants])); // should alert a nicely-formatted list

Comments

0

Use console.log(json[userWants]); instead of alert.

You can view the output in console by opening it in Chrome by using the shortcut Ctrl + Shift + J or by using Firebug for Firefox in Firefox.

Comments

Your Answer

Post as a guest

Required, but never shown

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.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.