1

I'm working with ExpressionEngine and have converted my channel entries into JSON, that works nicely.

What I am trying to do is populate a Sweet Alert 2 overlay with information from specific JSON objects using an ID stored in a data-* attribute.

Here is an example of the JSON:

var director_45 = {
  "title": "Andy H",
  "entry_id": 45,
}

And if I do a simple jQuery alert like this, it returns my name:

alert(director_45.title)

However, if I do something like this in jQuery:

$('.trigger-director').on('click', function() {
  var director_id = $(this).data('director');
  var director = 'director_' + director_id;
  alert(director.title);
});

With this HTML to fire it:

<div class="col-xs-6 col-md-3">
  <div class="director-box">
    <img src="/images/made/images/uploads/images/Andy_400_300_c1.jpg" class="img-responsive" width="400" height="300" alt="" />
    <h3>Andy H</h3>
    <p>Director</p>
    <a class="trigger-director" data-director="45">Find out more</a>
  </div>
</div>

The alert upon clicking the 'Find out more' link only shows "Undefined".

I've created a jsFiddle link here too - https://jsfiddle.net/zu103vxc/

Any idea what it is that I'm doing wrong and/or missing?

8
  • var director = window[ 'director_' + director_id]; global variables are properties of the window object and you can access them using array notation Commented Jun 28, 2016 at 11:14
  • director is not an object, director is a string 'director_45', ohh @JuanMendes, that one will come handy Commented Jun 28, 2016 at 11:14
  • Possible duplicate of JavaScript Dynamic Variable Names Commented Jun 28, 2016 at 11:17
  • @JuanMendes Interestingly the console says "Uncaught TypeError: Cannot read property 'title' of undefined" Commented Jun 28, 2016 at 11:17
  • @andy do some closer debugging, if there's a global variable named director_45, it will work Commented Jun 28, 2016 at 11:20

1 Answer 1

1

Use eval()

var director_45 = {
  "title": "Andy H",
  "entry_id": 45,
}

alert(director_45.title)

$('.trigger-director').on('click', function() {
  var director_id = $(this).data('director');
  var director = 'director_' + director_id;
  alert(eval(director).title);
});

or global variables

var director_45 = {
  "title": "Andy H",
  "entry_id": 45,
}
window.director_45 = director_45;
alert(director_45.title)

$('.trigger-director').on('click', function() {
  var director_id = $(this).data('director');
  var director = 'director_' + director_id;
  alert(window[director].title);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, decided to go along the global var route. Saved me a massive headache :)

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.