0

There is such a piece where how

$(document).on('click', '#calcA', function() {
    $("#calcASum").addClass("field");
    ($(this).is(":checked")) ? $("#calcAInfo").css("display", "") : $("#calcAInfo").css("display", "none");
});

$(document).on('click', '#calcB', function() {
    $("#calcBSum").addClass("field");
    ($(this).is(":checked")) ? $("#calcBInfo").css("display", "") : $("#calcBInfo").css("display", "none");
});

$(document).on('click', '#calcC', function() {
    $("#calcCSum").addClass("field");
    ($(this).is(":checked")) ? $("#calcCInfo").css("display", "") : $("#calcCInfo").css("display", "none");
});

only AB and C changes; I wanted to write through for ()

var item = ['A', 'B', 'C'];
for(var i=0; i<item.length; i++) {
    $(document).on('click', '#calc'+item[i], function() {
        $("#calc"+item[i]+"Sum").addClass("field");
        ($(this).is(":checked")) ? $("#calc"+item[i]+"Info").css("display", "") : $("#calc"+item[i]+"Info").css("display", "none");
    });
}

he adds one more function after the click function. It turns out inside the function already i = 3. There are other solutions to this problem? thanx

2
  • api.jquery.com/toggle Commented Nov 15, 2018 at 8:51
  • The easiest solution is to not use IDs with semantic meaning. Use DOM traversal to find the related Sum/Info fields or pair them with data- attributes. Commented Nov 15, 2018 at 8:56

1 Answer 1

1

The fact is that you are referencing an outer scoped variable.

You can have a look at this question: Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. What is wrong?

And in your case you can try this code :

var item = ['A', 'B', 'C'];
for(var i=0; i<item.length; i++) {
    const j = i;
    $(document).on('click', '#calc'+item[j], function() {
        $("#calc"+item[j]+"Sum").addClass("field");
        ($(this).is(":checked")) ? $("#calc"+item[j]+"Info").css("display", "") : $("#calc"+item[j]+"Info").css("display", "none");
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

It's not so much that it's an "outer scoped variable" - it's that the click event occurs after the for loop has completed, so the value of i has already changed by the time you click. Have a good read of this: stackoverflow.com/questions/111102/…

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.