show item request form when an unknown item is selected in select2

时光毁灭记忆、已成空白 提交于 2020-12-13 03:51:27

问题


I would like to use select2 to show a company search. If the company the user is looking for is not in the current dataset we need to show a company request form to add the data.

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 at https://jsfiddle.net/morenoh149/mf6Lxyc0/21/ any help appreciated


回答1:


You are using change:select but that is not a select2 event. The closest event to that is change.select2 but that is not what you want. The event you want is select2:select, which occurs whenever a result is selected.

Given your existing code, you've already set isTag to true so the rest of your code works as you expect:

}).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';
  }
});


来源:https://stackoverflow.com/questions/64722399/show-item-request-form-when-an-unknown-item-is-selected-in-select2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!