在select2中选择未知项目时显示项目请求表 [英] show item request form when an unknown item is selected in select2

查看:141
本文介绍了在select2中选择未知项目时显示项目请求表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用select2来显示公司搜索.如果用户要查找的公司不在当前数据集中,则需要显示公司请求表以添加数据.

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

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/任何帮助表示赞赏

jsfiddle at https://jsfiddle.net/morenoh149/mf6Lxyc0/21/ any help appreciated

推荐答案

您正在使用change:select,但这不是

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.

鉴于现有代码,您已经将isTag设置为true,因此其余代码可以按预期工作:

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

这篇关于在select2中选择未知项目时显示项目请求表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆