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.

1
  • or you can simply change currentPageTitle = ('pageTitle'+currentPosition); to currentPageTitle = eval('pageTitle'+currentPosition); Commented Feb 12, 2011 at 3:41

3 Answers 3

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.

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

1 Comment

@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.
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);

1 Comment

too late :) another way of doing it anyway.
-1

Without any other modifications, you can replace this line

currentPageTitle = ('pageTitle'+currentPosition);

with this:

currentPageTitle = window['pageTitle'+currentPosition];

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.