2

The click handler is accessing a data attribute on the element and setting a variable based on what is it, in this case 'option1'. I want to use the name of this variable to access a JSON object. But in the example it's returning 'undefined', as if it's looking for an array called 'thisOption'. How can I use this data attribute to bring back the correct JSON content?

// Note: thisOption returns "option1", which is correct.

jq = jQuery;

// Pass info
jq('.button').click( function() {
    var thisOption = jq(this).data('name');
    jq('#subscriptions .price').text(thisOption.monthly);
});

var option1 = {
    "name"      : "Super Pack",
    "monthly"   : "€10",
    "yearly"    : "€100",
    "gift"      : "Free €20 voucher"
};

3 Answers 3

1

If option1 is in the global scope then you can access it via the window object with a dynamic key:

jq('#subscriptions .price').text(window[thisOption].monthly);

The [] notation allows you to use variable property or key names.

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

2 Comments

Great, thanks! Why do you need to use the window object to access it?
If your jq(this).data('name') returns different variable names, you can only access them via the window object (if they are global) or if they are contained in another variable/object. In the answer you accepted, the option1 is hardcoded, so if your data-name has option2 it won't work.
1

You can access the option1 like below

jq('#subscriptions .price').text(window[thisOption].monthly);

Because option1 is in global scope, you can access it like window.option1. When option1 is a value of some variable, then you should access like window[thisOption]

Comments

1

I made some structure so we can see it clearly, you can also check it in jsfiddle.net

Heres the url: http://jsfiddle.net/8hTrr/3/

HTML

<a href="#" data-option="monthly" class="button">test</a>
<div id="subscriptions">
    <p class="price"></p>
</div>

JS

var option1 = {
    "name"      : "Super Pack",
    "monthly"   : "€10",
    "yearly"    : "€100",
    "gift"      : "Free €20 voucher"
};

jq = jQuery;

// Pass info
jq('.button').click( function() {
    var thisOption = jq(this).data('option');
    jq('#subscriptions .price').text(option1[thisOption]);    
});

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.