【问题标题】:select2 - Get the value of the clicked boxselect2 - 获取点击框的值
【发布时间】:2021-09-17 14:41:36
【问题描述】:

在我的 Select2 多选框中,我希望能够单击选定的框并获取它们相应的选项值(或对象)。
这是(简而言之)我到目前为止所拥有的:

$('#mySelect2').next('span').find('ul').on('click', '.select2-selection__choice', function (e) {
    console.log($('#mySelect2').select2('data'));
    alert($(this).data('select2-id'));
});

我搜索了 select2 数据对象,但没有任何与单击框和 select2-id 数据属性相关的内容 似乎是随机的。
我在哪里可以找到一些匹配的 id?

【问题讨论】:

    标签: jquery-select2


    【解决方案1】:

    可以试试下面的代码,使用 select2 - 选择和取消选择事件。

        $("#mySelect2").on("select2:select select2:unselect", function (e) {
    
                //get all items by, for multiple an array like ["9", "20"] will be returned
                var items= $(this).val();       
    
                //Last selected value
                var lastItem = e.params.data.id;
    
        })
    

    【讨论】:

      【解决方案2】:

      我想我找到了解决方法。
      似乎 select2 使用了渲染列表中的 title 属性。
      所以诀窍是在每个选项中使用这个属性作为 id。

      <select multiple id="states" name="states[]" class="select2">
         <option title="states-AL" value="AL">Alabama</option>
         <option title="states-CA" value="CA">California</option>
         <option title="states-MI" value="MI">Michigan</option>
         <option title="states-UT" value="UT">Utah</option>
         <option title="states-WY" value="WY">Wyoming</option>
      </select>
      
      $('#states').next('span').find('ul').on('click', '.select2-selection__choice', function (e) {
          alert($(this).attr('title'));
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-07
        • 1970-01-01
        • 1970-01-01
        • 2021-03-30
        • 1970-01-01
        相关资源
        最近更新 更多