RemeJuan
RemeJuan

Reputation: 863

Combine 2 parts to create a variable in jQuery

Not sure about the title.

I have got a list of variables, base name with a number:

var answerOption1 = "Agra";
var answerOption2 = "Chicago";
var answerOption3 = "Halong Bay";

With that I want to dynamically populate a select list randomly, 12 variables in total with an array of numbers.

$('<option>').val(theAnswer).addClass('fieldbox').text(answerOption + arr[i]).appendTo("#answers");

As it is its not working, its running into an error because answerOption is undefined, but I need it to include the number from the array before calling the value from the variable

Upvotes: 0

Views: 95

Answers (4)

Anthony Grist
Anthony Grist

Reputation: 38345

Retrieving from variables when you're generating the name dynamically is possible, but can be tricky depending on their scope. I'd be inclined to create an object with the variables in instead, like so:

var variableObject = {
    answerOption1 : "Agra",
    answerOption2 : "Chicago",
    answerOption3 : "Halong Bay"
}

Then you'd do:

$('<option>').val(theAnswer).addClass('fieldbox').text(variableObject["answerOption" + arr[i]]).appendTo("#answers");

Assuming, of course, that arr[i] has the dynamic part of the "variable" (it's now actually a property of an object) name, so 1, 2, 3, etc.

Upvotes: 0

Daniel Imms
Daniel Imms

Reputation: 50229

You should use a single array instead of 12 variables.

var answerOptions = [
    "Agra",
    "Chicago",
    "Halong Bay"
];

Then populate it however you want pointing to the index of the variable.

$('<option>')
    .val(theAnswer)
    .addClass('fieldbox')
    .text(answerOptions[i])  // <----
    .appendTo("#answers");

Upvotes: 1

Adil
Adil

Reputation: 148150

You need to define answerOption instead of variables and use indexer to access each element of array.

var answerOption  = ["Agra", "chicago", "Halong Bay"];
$('<option>').val(theAnswer).addClass('fieldbox').text(answerOption[i]).appendTo("#answers");

Upvotes: 1

Jason P
Jason P

Reputation: 27022

You can use bracket notation to access properties by key:

.text(window['answerOption' + arr[i]])

I used window since (I think) your variables are global. If they aren't, you'll need to put them in an object, and replace window with that object's name.

It might be better to create an actual array of the values:

var answerOptions = [
    "Agra",
    "Chicago",
    "Halong Bay"
];

.text(answerOptions[i])

Upvotes: 2

Related Questions