【问题标题】:Show select2 "pillboxes" in an input separate from dropdown在与下拉列表分开的输入中显示 select2“药盒”
【发布时间】:2021-10-02 17:26:46
【问题描述】:

我正在尝试在单独的输入中显示从 select2 下拉列表中选择的选项,然后从下拉列表中删除该选项。

到目前为止,我一直采用的方法是将下拉菜单设置为正常选择,然后单击,将单击选项的值添加为“选定选项输入”的新选定选项。

当我想从输入中删除选定的选项时,这一直给我带来问题,尽管我无法找到一种有效的方法将删除的选项添加回原始选择并且选择的其他方面有真的很笨拙。

引用 Shark Tank 企业家的话:“必须有更好的方法!”

下面是我正在尝试做的事情的模型以及我正在尝试做的现有代码:

function initCodeSelectTwo() {
  $('#codeDropdown').select2({
    width: "100%",
    ajax: {
      url: 'urlOne',
      dataType: 'json',
      type: 'GET',
      data: data
    }
  })

  var codeSelector = $('#codeSelector');

  $.ajax({
    type: 'GET',
    url: 'urlOne' // controller method gets options already assigned to item
  }).then((data) => {
    var option = new Option(data.Code, data.Code, true, true);
    codeSelector.trigger({
      type: 'select2: select',
      params: {
        data: data
      }, 
      multiple: true
    });
  })
}

function UpdateDropdown() {
  // using click instead of change because the dropdown has been configured to not close on click
  $('#codeDropdown').on('click', 'option', function(event) {

    var option = $(this).val();
    $('select box option[value="' + option + '"]').remove();
    $("#codeInput").append('<option value="' + option + '">' + option + '</option>');
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

我无法在 select2 文档中找到任何相关内容,希望能提供任何帮助!

【问题讨论】:

    标签: javascript html jquery jquery-select2


    【解决方案1】:

    您必须使用 select2 提供的事件对其进行编程。在您的情况下,select2:select 事件将捕获选定的选项,然后您可以对其进行编程以在另一个 div 中显示。

    这是一个工作示例:

    //initialize select2
     $('#options').select2();
    
    //initialize a global array to store the selected options
    let selectedOptionsArray = [];
    
    //select2 event to capture the selected value
    $('#options').on('select2:select', function(e) {
      let selectedOption = e.params.data;
      let optionIndex = selectedOption.element.index;
      let optionText = selectedOption.text;
      let optionValue = selectedOption.element.value;
      
      //check if option already exists in the array
      let index = selectedOptionsArray.indexOf(optionValue);
      if (index !== -1) {
        //do nothing if option exists
        return false;
      }
        
      //else, add the option value to the array
      selectedOptionsArray.push(optionValue);
      
      //append the option to the desired element
      $('ul.results').append(`<li>
                <button type="button" class="remove-option" data-value="${optionValue}" data-index="${optionIndex}" title="Remove item">
                  <span aria-hidden="true">&times;</span> ${optionValue}
                </button>
              </li>`);
    });
    
    
    //click event listener on the appended to remove it
    $(document).on('click', '.remove-option', function() {
        //remove the option from global array
      let findIndex = selectedOptionsArray.indexOf($(this).attr('data-value'));
      if (findIndex !== -1) {
        selectedOptionsArray.splice(findIndex, 1);
      }
      
      //remove the option element
      $(this).parent().remove();        //here, parent() refers to the li 
    });
    
    //fetch the current values
    $('#fetchValues').click(function() {
      console.log(selectedOptionsArray);
      $('#values').html(selectedOptionsArray);
    });
    select{
      display: block;
    }
    
    ul.results{
      display: flex;
      width: 200px;
      margin-top: 1rem;
      overflow: auto;
      padding: 1rem;
      background-color: #fff;
      border: 1px solid #ddd;
      list-style-type: none;
    }
    
    ul.results li{
      margin-left: 0.5rem;
    }
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"/>
    <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>
    
    <select id="options">
      <option selected disabled>Select Option</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
      <option value="4">Option 4</option>
      <option value="5">Option 5</option>
      <option value="6">Option 6</option>
      <option value="7">Option 7</option>
    </select>
    
    <ul class="results">
    
    </ul>
    
    <button id="fetchValues">
      Fetch Values
    </button>
    
    <div id="values"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-11
      • 1970-01-01
      • 2018-04-23
      • 2013-06-11
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多