2

I'm trying to bind an onChange event to 7 dropdowns inside a loop. But when any of dropdown changes, the onChange event for the last one is always executed.

$(function () {
    for (var i = 1; i <= 7; i++) {
        $('select[id$="bodysys' + i + '"]').change(function () {
            if (this.value == "99")
                enabletextbox($('input[id$="bodysys' + i + 'spec"]')[0]);
        });
    }
}

How to make onChange work for all elements separately?

0

2 Answers 2

7

This is called the last one only problem, and is solved using a closure:

$(function () {
    for (var i = 1; i <= 7; i++) {
        (function (i) {
            $('select[id$="bodysys' + i + '"]').change(function () {
                if (this.value == "99")
                    enabletextbox($('input[id$="bodysys' + i + 'spec"]')[0]);
            });
        })(i);
    }
}

It creates a new scope, so when i is changed in the original scope, it will not be changed in the old scope.

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

Comments

0
$('select[id*="bodysys"]').each(function (index) {
        $(this).change(function () {
            if ($("option:selected", this).val() == "99")
                enabletext($('input[id$="bodysys' + (index + 1) + 'spec"]')[0]);
        });
    });

This way works too.

Comments

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.