【问题标题】:change onchange event of dynamic created select to populate another dynamic created select更改动态创建的选择的 onchange 事件以填充另一个动态创建的选择
【发布时间】:2017-10-13 06:36:10
【问题描述】:

我有 2 个 ID 为 select1otherselect1 的选择框。我在 select1 上触发了一个 onchange 事件以将数据附加到 otherselect1

现在我通过将 id 增加到 +1 来动态添加多个这些选择框组合。例如:select2 和 otherselect2select3 和 otherselect3

问题是我如何编写 onchange 事件,以便如果我更改 select2 它只会影响 otherselect2 的数据,对于 select3otherselect3

代码:

    $('.select_type').on('change', function() {
        var channel_type = $(this).val();

        return  $.ajax({
            url: __SITE.baseUrl ,
            data: "channel_type=" + channel_type
            success: function (data)
            {
                if (data) {
                    data = JSON.parse(data);
                    var total = data.length;
                    $(this).next('.select_user').html('');
                    $(this).next('.select_user').append($('<option/>', {value: '', text : 'Choose One'}));
                    for(var i=0; i < total; i++)
                    {
                        $(this).next('.select_user').append($('<option/>', {value: data[i]['id'], text : data[i]['name']}));
                    }
                }
            }
        });
    });

【问题讨论】:

    标签: javascript jquery onchange


    【解决方案1】:

    分别为所有selectotherselect 保留相似的类名,并使用next() 将从.select 下拉列表中选择的数据附加到.otherselect。查看下面的 sn-p 以供参考。

    $('.select').on('change', function() {
      $(this).next('.other-select').append($('<option>', {
        text: $(this).val()
      }));
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div>
      <select class="select">
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
    </select>
      <select class="other-select">
    </select>
    </div>
    <div>
      <select class="select">
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
    </select>
      <select class="other-select">
    </select>
    </div>
    <div>
      <select class="select">
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
    </select>
      <select class="other-select">
    </select>
    </div>

    【讨论】:

    • 不知何故它在我的情况下不起作用。这是我的js代码。不允许我粘贴代码。说太长了。在问题中编辑它。
    • $(this).next('.other-select').val();给出未定义。
    • 在 fiddler 中分享您的代码,以便查看。
    • 感谢拉杰什的帮助
    【解决方案2】:

    我自己解决了。

    在所有select1中添加onclick="javascript_function(this.id)",并在javascript_function中使用这个id调用对应的otherselect1

    【讨论】:

      猜你喜欢
      • 2015-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 2016-04-18
      • 2018-01-11
      • 1970-01-01
      相关资源
      最近更新 更多