最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Initialize onchange event inside a loop - Javascript - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Mar 4, 2019 at 7:19 Umair Ayub 21.5k14 gold badges82 silver badges154 bronze badges asked Mar 21, 2012 at 12:53 etldsetlds 5,8902 gold badges24 silver badges31 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 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.

$('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.

发布评论

评论列表(0)

  1. 暂无评论