Benjamin Lawson Benjamin Lawson - 4 months ago 11
Javascript Question

How to set an element to the value of a variable using Jquery

I am building a portfolio website. The user can click through my work using left and right arrows. The left and right arrows set the variable x to 1,2, or 3 and sends it through a function "workSelection". As the user clicks through the work I want it to update work title to match the variable of the selected work (1,2 or 3).

var workTitle1 = "Work 1";
var workTitle2 = "Work 2";
var workTitle3 = "Work 3";

function workSelection(x)
{
var loop = 1;
while (loop < 4)
{
if (x == loop)
{
$("#workTitle").html('workTitle'+loop);
}
loop++;
}
}


How can I change $("#workTitle").html('workTitle'+loop); to display the value of workTitle1, workTitle2, workTitle3. Instead now it is only showing a string with value of "workTitle1", etc... not the value of the variable itself.

Thanks for any help!

Answer

You can use window['workTitle'+ loop]

var workTitle1 = "Work 1";
var workTitle2 = "Work 2";
var workTitle3 = "Work 3";

function workSelection(x)
{
    $("#workTitle").html(window['workTitle'+ x]);
}

EDIT: There is no need to loop, I just answered the question how to change $("#workTitle").html('workTitle'+loop) to display the value of workTitle1 :)