0

I'm stumped on why this for loop does not seem to be incrementing properly.

This is probably too much context, but... First, I use razor to create a bunch of panels from the given model with navigation buttons:

@foreach (Con c in Model.cList)
{
    <div id="c@(c.Id)Panel" class="panel panel-default" hidden>
        <p id="cText" style="overflow:scroll; height:400px;">@c.Content
        </p>
        <button type="button" class="btn btn-info" id="c@(c.Id)PrevButton">Previous</button>
        <button type="button" class="btn btn-info" id="c@(c.Id)NextButton">Next</button>
    </div>
}

Then, I get a list of all of the selected checkboxes within a particular panel to get the user's desired navigation behavior:

var checkboxes = [];
$('#selectionPanel input:checked').each(function () {
    checkboxes.push($(this).attr('value'));
});

Then I use that information to map navigation buttons to other corresponding panels based on the user's selection:

for (var i = 0; i < (checkboxes.length - 1) ; i++) {
    $("#c" + checkboxes[i] + "NextButton").on("click", function () {
        $("#c" + checkboxes[i] + "Panel").slideUp("500");
        $("#c" + checkboxes[i + 1] + "Panel").show("200");
    });
 }

However, it appears that var i is incremented before the loop gets to the slideup and show commands. For example the following loop works perfectly:

for (var i = 0; i < (checkboxes.length - 1) ; i++) {
    var j = i;
    $("#c" + checkboxes[j] + "NextButton").on("click", function () {
         $("#c" + checkboxes[j] + "Panel").slideUp("500");
         $("#c" + checkboxes[j + 1] + "Panel").show("200");
    });
}

Glad I got it working, but really confused on why the simple for loop didn't work as expected. Any ideas?

jakeh
  • 31
  • 5

0 Answers0