使用WordPress的jQuery选择2

我正在WordPress内部使用jQueryselect2。

我有一个这样的HTML表。

我需要这里,如果用户单击Bob SMith and admin,它将转换为具有多个选择的select2下拉列表。

但当我点击它时,它看起来如下所示

如果我再次单击,下拉菜单如下所示。

当我单击任意值时,它如下所示

我的jQuery代码如下

(function($) {
  var states = [];
  
  $(document).ready(function() {
    $(".volunteer").on("click", function(event) {
      // Check if select is already loaded
      if (!$(this).has("select").length) {
        var cellEle = $(this);
        var cellId = this.id;

        // Populate select element
        cellEle.html(`<select class="js-example-basic-multiple" multiple="multiple">
            <option value="AL">Alabama</option>
            <option value="WY">Wyoming</option>
            </select>`);

        // Initialise select2
        let selectEle = cellEle.children("select").select2();
        
        if(states[cellId]){
            // preselect existing value
          selectEle.val(states[cellId]);
          selectEle.trigger('change'); 
        }

        selectEle.on("select2:close", function(event) {
          // Get selected value
          selectedValue = selectEle.select2('data')[0]['text'];

          // Update array          
          states[cellId] = selectedValue.id;
          
          // Destroy select2
          selectEle.select2('destroy');
          
          // Change html to just show the value
          cellEle.html(selectedValue.id);
        });
      }
    });
  });
})(jQuery)

我的HTML代码如下所示

<td class="volunteer" id="47">Bob SMith and admin</td>

解决方案

点击两次

在单元格上的第一次单击将初始化选择器2,然后第二次单击将告诉选择器2显示下拉菜单。若要只需要一次单击,您可以在selt2初始化后调用https://select2.org/programmatic-control/methods中介绍的Open方法。

// Initialise select2
let selectEle = cellEle.children("select").select2();
// Open the select2 dropdown
selectEle.select2('open');

替换选定内容

当单击值selt2被销毁时,.html()调用应该用所选值替换SELECT,但它不能正常工作,因为id属性不存在于存储值上,这将导致单元格恢复为正常的SELECT。

处理"select2:close"事件的代码包含selectedValue = selectEle.select2('data')[0]['text'];行,该行将第一个选定值[0]的文本放入变量selectedValue。在此之后,使用cellEle.html(selectedValue.id);更新单元格的HTML,但此时selectedValue仅包含文本(例如&Quot;Alabama";),因此没有.id属性。要解决此问题,可以将ID和文本存储在数组中,然后在需要的地方使用,例如:

// Store the id and text of all selected values in the array
selectedValue = selectEle.select2('data').map(function(value) {
  return { id: value.id, text: value.text }; 
});

// Get an array of IDs for the selected values (for preselecting values when select2 loads)
selectEle.val(states[cellId].map(function(value) { return value.id })).trigger('change');

// Get a comma separated string of the selected values (for populating the text in the cell)
cellEle.html(states[cellId].map(function(value) { return value.text; }).join(','));

多选模式- 允许多项选择的一个例子是https://jsfiddle.net/aqgbxz1d/,也包含在下面的答案中。根据问题中的multiple="multiple"属性,这似乎是所需的模式。

该示例已更新为不再使用select2:close事件。相反,它使用change事件来存储值更改,并使用文档上的第二个click事件处理程序在用户单击页面上的其他位置时销毁selt2下拉列表。考虑到您要尝试实现的目标,这似乎是一种更好的方法,因为它为选择多个值留下了空间。

单选模式- 从评论来看,单选模式似乎是必需的。只允许单一选择的一个例子是https://jsfiddle.net/9jcnwbt2/1/。如果需要单选模式,则需要:

  • 删除多个属性multiple="multiple"
  • 添加空白选项<option></option>
  • 您还可以复制文档单击事件中的代码,该事件将销毁selt2并将HTML更新到Change事件中。
数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
(function ($) {
  var states = [];

  $(document).ready(function () {
    $(".volunteer").on("click", function (e) {
      // Check if select is already loaded
      if (!$(this).has("select").length) {
        var cellEle = $(this);
        var cellId = this.id;

        // Populate select element
        cellEle.html(`<select class="js-example-basic" multiple="multiple">
                    <option value="AL">Alabama</option>
                    <option value="WY">Wyoming</option>
                    </select>`);

        // Initialise select2
        let selectEle = cellEle.children("select").select2({placeholder: "Select a value"});

        // Open the select dropdown so user doesn't have to click twice
        selectEle.select2('open');

        // Check if there is an existing value for this cell
        if (states[cellId]) {
          // preselect existing value
          selectEle.val(states[cellId].map(function (value) {
            return value.id
          })).trigger('change');
        }

        // Attach event handler to store value changes
        selectEle.on('change', function (e) {

          // Get selected values
          selectedValues = $(this).select2('data');

          // Update the states array with id and text of selected 
          // values. The id is needed to restore the values if select2
          // is reloaded on this cell. The text is required to generate
          // the replacement text shown in the cell
          states[cellId] = selectedValues.map(function (value) {
            return {
              id: value.id,
              text: value.text
            };
          });
        });
      }

      // Don't propagate the event
      // This prevents this document click handler from executing which would
      // remove select2 by calling destroy
      e.stopPropagation();
    });
  });

  // Attach event handler to document to capture any clicks
  // This will be triggered for all clicks on the page, except those 
  // captured by the method described above this prevents this firing
  // with e.stopPropagation()
  // Which this is called select2 on any cells must be destoryed and their 
  // text value populated
  $(document).on('click', function (e) {
    // Loop through all select2 elements
    $('.js-example-basic').each(function (idx) {
      // Get the ID of the cell that's been selected
      let cellId = $(this).parent().attr('id');

      // Destroy select2 on this element
      $(this).select2('destroy');

      // Change html on the parent element (td) to just show the value
      if(states[cellId] && states[cellId].length > 0){
        $(this).parent().html(states[cellId].map(function (value) {
          return value.text;
        }).join(','));
      } else {
        $(this).parent().html("Select a value...")
      }
    });
  });

})(jQuery)
.js-example-basic {
  width: 200px;  
}

thead{
    font-weight: bold;
}

table, th, td {
  border: 1px solid black;
}

tr {
  height: 36px;
}

td {
  width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<table>
  <thead>
    <tr>
      <td>Table Header 1</td>
      <td>Table Header 2</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="volunteer" id="47">Select a value...</td>
      <td class=""></td>
    </tr>
    <tr>
      <td class="volunteer" id="48">Select a value...</td>
      <td class=""></td>
    </tr>
  </tbody>
</table>

相关文章