0

I have 2 variables in a script tag that get populated with string values. I also have an .each loop that goes through each select box I have on the page. I want a way to append the index value of the loop to the name of the variable, and retrieve its value.

var secQuestion1 = "bla"
var secQuestion2 = "bla"

    selectbox.each(function( index ) {
       var question = ['secQuestion' + (index+1) ];
       console.log("question = ", ['secQuestion' + (index+1)] )
    });

I thought I might be able to use bracket notation to retrieve the value. Any ideas on how to do this, so on each index in the loop I would get my questions values?

2
  • Interesting, I don't see any jQuery here. Have you looked at the documentation at all? docs.jquery.com Commented Jul 27, 2012 at 19:27
  • Please add the code that assigns the value to selectbox Commented Jul 27, 2012 at 19:32

2 Answers 2

2

I'd use an array here, for example:

var arrQuestions = ["question A", "question B", "questionC"];

selectbox.each(function( index ) {
   var question = arrQuestions[index];
}
Sign up to request clarification or add additional context in comments.

Comments

1

it depends in what context your code is running, if your variables are global then you can do

window['secQuestion' + (index+1)]

you can also put them in an object and access them that way

var obj = {
    secQuestion1: "bla",
    secQuestion2: "bla"
};
selectbox.each(function( index ) {
   console.log("question = ", obj['secQuestion' + (index+1)] )
});

3 Comments

That's a terrible, unmaintainable technique. Please stop advocating global variables to a newbie.
@Alex Weinstein, I answered his question, I did not advocate anything. Just because you don't like global variables does not mean people should not know about them and understand how to use them.
I here you Alex about the global variable using the window approach but the var obj approach works perfectly and the variable is not global as its inside a jquery ready function. Thanks again.

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.