簡體   English   中英

在 select2 中選擇未知項目時顯示項目請求表

[英]show item request form when an unknown item is selected in select2

我想使用 select2 來顯示公司搜索。 如果用戶要查找的公司不在當前數據集中,我們需要顯示公司請求表以添加數據。

html

<head>
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
  <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
</head>
<body>
<select class="js-example-basic-single" name="company">
  <option value="1">(FB) Facebook</option>
  <option value="2">(AAPL) Apple</option>
  <option value="3">(NFLX) Netflix</option>
  <option value="4">(GOOG) Alphabet</option>
</select>
<form style="margin: 100px 0 0 0; display: none">
  <h2>
    Company not found
  </h2>
  <button>
    Add Company?
  </button>
</form>
</body>

javascript

/**
 * Requrirements:
 * 1) indicate in dropdown that the user will be adding the company. Maybe by displaying "Add: GOOG"
 * 2) unhide company request form when a new company is selected.
 */
$(document).ready(function() {
  let elm = $('.js-example-basic-single');
  elm.select2({
    placeholder: "Company",
    tags: true,
    createTag: function(params) {
      console.log('createTag', params);
      return {
          id: params.term,
          text: params.term.toUpperCase()
      }
    },
    insertTag: function(data, tag) {
        tag.isTag = true;
        data.push(tag);
    },
  }).on("change:select", function(e) {
      console.log('select');
      var data = e.params.data;
      var requestForm = document.querySelector('form');
      if (data.isTag) {
          console.log('local tag selected', data);
          requestForm.style.display = 'block';
      } else {
          requestForm.style.display = 'none';
      }
  });
});

jsfiddle 在https://jsfiddle.net/morenoh149/mf6Lxyc0/21/任何幫助表示贊賞

您正在使用change:select但這不是select2 event 最接近的事件是change.select2但這不是您想要的。 您想要的事件是select2:select ,只要select2:select了結果就會發生。

鑒於您現有的代碼,您已經將isTag設置為true因此其余代碼按您的預期工作:

}).on("select2:select", function(e) {
  console.log('select');
  var data = e.params.data;
  var requestForm = document.querySelector('form');
  if (data.isTag) {
    console.log('local tag selected', data);
    requestForm.style.display = 'block';
  } else {
    requestForm.style.display = 'none';
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM