2

I'm just trying to make a list of questions with hidden answers that shows upon click. My code hides all divs, but when I click on the anchors, only the last box is toggled. In this case, every anchor toggles the 5th box, and not their own.

for(var i=1; i<6; i++){
    var x = i+"";
    $("#box"+ x).hide();
    $("#feature"+x).click(function(){
        $("#box"+x).toggle(400);
    });
}

My basic HTML looks like this, but with 5 pairs:

<p><a id="feature1" href="#">1. Absent Message</a></p>
<div id="box1">Stuff here 1</div>
<p><a id="feature2" href="#">2. Alarm Setting</a></p>
<div id="box2">Stuff here 2</div>

If I wrote out the functions without using the for loop and string concatenation, the functions do what I want them to. Can someone point me in the right direction? Am I doing something wrong with the string manipulation?

1 Answer 1

5

Your problem is that x is shared between all copies of the loop, so in the end it's always 5, and $("#box"+x) will always be $("#box5") when it's appending at click time. An easier way would be classes, like this:

<p><a class="feature" href="#">1. Absent Message</a></p>
<div class="box">Stuff here 1</div>

Then find it relatively, like this:

$(".box").hide();
$(".feature").click(function() {
  $(this).parent().next(".box").toggle(400);
});

If that's not an option, you need to provide the necessary scope to your loop, like this:

for(var i=1; i<6; i++){
  (function(x) {
    $("#box"+ x).hide();
    $("#feature"+x).click(function(){
      $("#box"+x).toggle(400);
    });
  })(i);
}

By doing this we're passing i into the anonymous function, which gets its own copy called x, not a shared variable scoped to whatever function your for loop is in (which is what's currently happening).

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

1 Comment

Nick, thanks for explaining the logic behind my variable/scope problem. Your solution worked flawlessly as well as providing a good example of how dynamic selectors should be used. Hope this helps other newbies.

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.