0

So this is my problem.

pageTitle1 = ('This is page one');
pageTitle2 = ('This is page two');
pageTitle3 = ('This is page three');

currentPageTitle = ('pageTitle'+currentPosition);

$("#pageNumber").html(currentPageTitle);

I'm trying to display the current page title to the screen based on the currentPosition of the slide I am on. The issue I'm having is the code above is displaying "pageTitle1" to the screen when I need it to display "This is page one". I'm newish to javascript so I have a feeling this an easy fix but days of googling has yielded me nothing.

Mike
  • 3
  • 1
  • 2
  • or you can simply change currentPageTitle = ('pageTitle'+currentPosition); to currentPageTitle = eval('pageTitle'+currentPosition); – naveen Feb 12 '11 at 03:41

3 Answers3

5

Use an array instead of naming each variable individually.

var pageTitles = [
 'This is page one',
 'This is page two',
 'This is page three'
];

var currentPageTitle = pageTitles[currentPosition];

Reason why your code is not working is because it is simply adding the two strings "pageTitle" and currentPosition and assigning the concatenated string to currentPageTitle. What you instead want is to get the value stored in the variable having that name. Assuming you are creating these in the global scope (which is not a good thing btw), you can do:

var currentPageTitle = window['pageTitle'+currentPosition];

However, going with arrays is a better approach.

Anurag
  • 140,337
  • 36
  • 221
  • 257
  • @Mike: if this answer solved your problem, you should mark it as "accepted" by clicking the hollow green checkmark to the left of the question. – Matt Ball Feb 12 '11 at 03:54
1

Do something like this.

var pageTitle = new Array();
pageTitle.push('This is page one');
pageTitle.push('This is page two');
pageTitle.push('This is page three');

currentPageTitle = (pageTitle[currentPosition]);
$("#pageNumber").html(currentPageTitle);

Or simply use eval (really super unrecommended)

var currentPageTitle = eval('pageTitle'+currentPosition);
Community
  • 1
  • 1
naveen
  • 53,448
  • 46
  • 161
  • 251
-1

Without any other modifications, you can replace this line

currentPageTitle = ('pageTitle'+currentPosition);

with this:

currentPageTitle = window['pageTitle'+currentPosition];
Mark Eirich
  • 10,016
  • 2
  • 25
  • 27