0

I have the following object which has been passed from PHP

    var phpVars = {"embedCode0":"<iframe id="player_0"></iframe>",
                   "embedCode1":"<iframe id="player_1"></iframe>",
                   "embedCode2":"<iframe id="player_2"></iframe>",
                  };

My HTML contains a matching number of <div class="video-container"></div> elements. I want to append each of the array items to each div in order. So that "embedCode0" is appended to the first div, "embedCode1" is appended to the second div and so on.

My jQuery function looks like this:

    function vids(){
        var $video = $('div.video-container');

        $video.each(function(index) {
            var $iframe = phpVars.embedCode + index;
            $(this).append($iframe);
        });
    }

The function returns NaN. I have attempted to convert the index to a string but have not been able to succeed.

How can I increment the "embedCode" string?

chalky
  • 97
  • 1
  • 6
  • It could be my lack of understanding but the question that is marked as a duplicate does not answer how I increment the string automatically which is what I needed to know. It only seems to provide a different notation for accessing a certain item. But please feel free to clarify if that's not the case. – chalky Jul 24 '14 at 14:15
  • It gives the same answer that Mritunjay did. You have to use the bracket notation (`[]`) instead of the dot notation (`.`) to be able to do what you are trying to do - that is the key. Incrementation is not important here. I agree that the marked question does not write the exact code for YOU, but that is not the point here. It answers what the problem is with your code. You should actually be happy when you only get a pointer, instead of someone writing the exact code for you. – kapa Jul 24 '14 at 14:22

1 Answers1

1

You should be trying this

var $iframe = phpVars["embedCode" + index];

instead of

var $iframe = phpVars.embedCode + index;

When you are saying phpVars.embedCode + index it tries to first evaluate phpVars.embedCode and after that concatenating index in that.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68