【问题标题】:Get selected option in Select2 event, when multiple options can be selected在 Select2 事件中获取选定的选项,当可以选择多个选项时
【发布时间】:2016-09-18 19:28:43
【问题描述】:

在收听select2:select 事件时如何获取刚刚选择的<option>?请注意,这在使用单选时很简单,因为当只选择一个选项时,它必须是刚刚选择的那个。我还希望能够找到使用多选时刚刚选择的选项(<select multiple>)。

select2:unselect 事件中,未选中的<option> 可通过e.params.data.element 获得,但在select2:select 事件中并非如此。我看不出<option> 不可用的原因,因为它是在此时创建的。然而,对于select2:selecting 事件,<option> 尚未创建,显然在事件触发时无法使用。

【问题讨论】:

    标签: jquery-select2 html-select jquery-select2-4


    【解决方案1】:

    我使用以下方法来获取 Select2 中选择的电流(适用于版本 4 及更高版本):

    // single value
    var test = $('#test');
    test.on("select2:select", function(event) {
      var value = $(event.currentTarget).find("option:selected").val();
      console.log(value);
    });
    

    更新:多选值(有和没有最后选择)

    // multi values, with last selected
    var old_values = [];
    var test = $("#test");
    test.on("select2:select", function(event) {
      var values = [];
      // copy all option values from selected
      $(event.currentTarget).find("option:selected").each(function(i, selected){ 
        values[i] = $(selected).text();
      });
      // doing a diff of old_values gives the new values selected
      var last = $(values).not(old_values).get();
      // update old_values for future use
      old_values = values;
      // output values (all current values selected)
      console.log("selected values: ", values);
      // output last added value
      console.log("last added: ", last);
    });
    

    【讨论】:

    • 这不会只是在选中的选项中找到第一个选项的值吗?我想获得刚刚选择的选项,如果选择了多个选项。
    • 我建议不要使用 .val();
    • 是的。要获得刚刚选择的选项,我必须保留所有选定选项的列表,并查看现在选择了哪个选项,但不在列表中。还是你有更好的主意?
    • 也许你应该澄清你的问题,例如在标题中添加多选。
    • 好主意。完成:)
    【解决方案2】:
     $('#test').on('select2:select', function(e) {
      var data = e.params.data;
      console.log(data);
     
    });
    

    【讨论】:

      猜你喜欢
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      相关资源
      最近更新 更多