jQuery 我需要在 Select2 中添加“添加新项目”选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38635800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:11:33  来源:igfitidea点击:

I need to add "Add new item" option in Select2

jqueryjquery-select2jquery-select2-4

提问by Prabhakarank

I want to add a button in first element of the list to "Add new item". If user clicks on that button I need to open a pop-up and get the input from users. How to do this in select2 plugin? Is any default options for this (or) need to customize this?

我想在列表的第一个元素中添加一个按钮来“添加新项目”。如果用户单击该按钮,我需要打开一个弹出窗口并获取用户的输入。如何在 select2 插件中做到这一点?是否有任何默认选项(或)需要对此进行自定义?

回答by user2976753

Here's my approach

这是我的方法

$('#select2')
    .select2()
    .on('select2:open', () => {
        $(".select2-results:not(:has(a))").append('<a href="#" style="padding: 6px;height: 20px;display: inline-table;">Create new item</a>');
})

enter image description here

在此处输入图片说明

回答by moped

basically what Kld suggested, but without additional buttons as I understand OP wants to use first option of selectto trigger new value modal. It checks the value when select2:close event is triggered and if "NEW"is selected, prompts for new value, adds at the end of selectbox and selects it.

基本上是 Kld 建议的,但没有其他按钮,据我所知 OP 想要使用第一个选项select来触发新值模式。它在 select2:close 事件被触发时检查值,如果"NEW"被选中,提示输入新值,在select框的末尾添加并选择它。

NOTE: I've disabled search in input and added placeholder

注意:我在输入中禁用了搜索并添加了占位符

$(function () {
  $(".select2")
  .select2({
    placeholder: 'Select type',
    width: '50%',
    minimumResultsForSearch: Infinity
  })
  .on('select2:close', function() {
    var el = $(this);
    if(el.val()==="NEW") {
      var newval = prompt("Enter new value: ");
      if(newval !== null) {
        el.append('<option>'+newval+'</option>')
          .val(newval);
      }
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select id="mySel" class="select2">
  <option></option>
  <option value="NEW">Add new type</option>
  <option>Car</option>
  <option>BUS</option>
  <option>TWO</option>
  <option>THREE</option>
</select>

回答by Patrick Otto

  $('#my-select2').select2().on('select2:open', function () {
            var a = $(this).data('select2');
            if (!$('.select2-link').length) {
                a.$results.parents('.select2-results')
                        .append('<div class="select2-link"><a>New item</a></div>')
                        .on('click', function (b) {
                            a.trigger('close');

                            // add your code
                        });
      }
   });

enter image description here

在此处输入图片说明

回答by Kld

You can add a new option to the select2 this way

您可以通过这种方式向 select2 添加新选项

$('button').click(function(){
  var value = prompt("Please enter the new value");
  $(".mySelect")
    .append($("<option></option>")
    .attr("value", value )
    .text(value ));

})

回答by Jeetesh Vagh

HTML Code

HTML代码

<div class="input-group">
<select class="form-control select2-hidden-accessible" data-plugin="select2" id='select' tabindex="-1" aria-hidden="true">
    <optgroup label="Select Cutomer">
    <option value="AK">Zilal</option>
    <option value="HI">Ajay</option>
    </optgroup>
    </select>
    <div class="wrapper" id="wrp" style="display: none;">
    <a href="#" id="type" class="font-weight-300" data-target="#mdl_Item" data-toggle="modal">+ Add New Vendor</a>
    </div>
    </div> 

JavaScript Code:

JavaScript 代码:

$(document).ready(function () {

    var flg = 0;

    $('#select').on("select2:open", function () {
      flg++;
      if (flg == 1) {
        $this_html = jQuery('#wrp').html();
        $(".select2-results").append("<div class='select2-results__option'>" + 
      $this_html + "</div>");
      }
    });

});

Output looks like as shown below:

输出如下所示:

enter image description here

在此处输入图片说明

回答by Sharagoz

A modified version of modped's answer that I used for multi select

我用于多选的 modped 答案的修改版本

$('.select2').select2().on('select2:close', function() {
  var el, newOption, newval;
  el = $(this);
  if (el.val() !== null && el.val()[0] === '') {
    el.val(el.val().slice(1));
    el.trigger('change');
    newval = prompt("Enter new value:");
    if (newval !== null && newval !== '') {
      newOption = new Option(newval, newval, true, true);
      return el.append(newOption).trigger('change');
    }
  }
});

回答by user3405326

jQuery("#select2-"+yourelementid+"-container").off().on('click',function(){
                        jQuery("#yourelementid"_add").remove();
                        jQuery("#select2-"+yourelementid+"-results").after("<div id='"+yourelementid+"_add' >optionnameforadding</div> ").promise().done(function(){
                            jQuery("#"+yourelementid+"_add").off().on('click',function(){
                            //  yourfunctionfordisplayingdiv
                            });
                        });
                    }); 

you can add html content after the ul list - select2-"+yourelementid+"-results , and do whatever you can with it. just set the result as the val of the select box

您可以在 ul 列表之后添加 html 内容 - select2-"+yourelementid+"-results ,并对其进行任何操作。只需将结果设置为选择框的 val

check the image out

检查图像

回答by David Bigelow

After digging around on this subject for quite some time... I thinkI have a solution for this problem.

在这个主题上挖掘了很长一段时间之后......我我有一个解决这个问题的方法。

I noticed that Select2 seems to be creating its own structure within the DOM -- irrespective of the Select that you are interacting with. -- This also appears to be completely independent of the Select you may have created elsewhere in the DOM.

我注意到 Select2 似乎在 DOM 中创建自己的结构——与您正在交互的 Select 无关。-- 这似乎也完全独立于您可能在 DOM 中的其他地方创建的 Select。

So.... After some fiddling around - I came up with the following code:

所以......经过一些摆弄 - 我想出了以下代码:

First:Create a global binding to all Selects in the DOM. This is only for setting a temporary reference to 'what' the current user is working with -- creating a global variable that can be used later.

第一:创建一个全局绑定到 DOM 中的所有 Selects。这仅用于设置对当前用户正在使用的“内容”的临时引用——创建一个以后可以使用的全局变量。

      $('select').select2().on('select2:open', function() {
                        // set a global reference for the current selected Select
                        console.log('found this ---> '+$(this).attr('id'));
                        if (typeof tempSelectedObj === 'undefined') {
                            tempSelectedObj = null;
                        }
                        tempSelectedObj = this;
                    });

Second:Create a document 'keyup' event that is mapped to the Select2 temporary INPUT and select2-search__field class. This will capture all key events for the Select2 INPUT. But in this case, I have added a keyCode === 13 (return character) to init the magic.

第二:创建映射到 Select2 临时 INPUT 和 select2-search__field 类的文档 'keyup' 事件。这将捕获 Select2 INPUT 的所有关键事件。但在这种情况下,我添加了一个 keyCode === 13(返回字符)来初始化魔法。

    $(document).on('keyup','input.select2-search__field',function (e) {
                    // capture the return event
                    if (e.keyCode === 13) {

                        var newValue = $(this).val();
                        console.log('processing this: '+newValue);

                        // create new option element
                        var newOpt = $('<option>')
                            .val(newValue)
                            .text(newValue);

                        // append to the current Select
                        $(tempSelectedObj)
                            .append(newOpt);

                        // apply the change and set it
                        $(tempSelectedObj)
                            .val(newValue)
                            .select2('close');
                    }
                })

When a return character is detected, the following happens.

当检测到返回字符时,会发生以下情况。

  • capture the current value
  • create a new DOM Option Element (jQuery)
  • set the value and text of the new Option Element
  • append the new Option Element to the tempSelectedObj variable (jQuery)
  • trigger the Select2 to close
  • set the value of the Select2 to the new value appended
  • trigger the final Select2 change to display the new Option
  • DONE!
  • 捕获当前值
  • 创建一个新的 DOM 选项元素 (jQuery)
  • 设置新选项元素的值和文本
  • 将新的 Option 元素附加到 tempSelectedObj 变量 (jQuery)
  • 触发 Select2 关闭
  • 将 Select2 的值设置为附加的新值
  • 触发最终的 Select2 更改以显示新选项
  • 完毕!

Obviously the two sections of code are required for this example, but I think it is a pretty slick approach for a problem which a lot of people seem to be struggling with. And it is generic enough that it could be tailored for other purposes with ease.

显然,此示例需要两段代码,但我认为对于很多人似乎都在努力解决的问题,这是一种非常巧妙的方法。而且它足够通用,可以轻松地为其他目的量身定制。

Hope this helps! I have struggled with this for sometime.

希望这可以帮助!我已经为此挣扎了一段时间。

Here is a working example:

这是一个工作示例:

https://jsfiddle.net/h690bkmg/1/

https://jsfiddle.net/h690bkmg/1/

回答by Pavan Hukerikar

Try this it is working for me

试试这个它对我有用

$('#yourDropdownId').select2({              
              ajax: {
                  url: productUrl, 
                  dataType: 'json',
                  data: function (params) {
                    var query = {
                      search: params.term,
                      page: params.page || 1
                    }

                    // Query parameters will be ?search=[term]&page=[page]
                    return query;
                  },processResults: function (data, params) {       
                      console.log(data)                                        
                          return {
                              results: $.map(data.items, function (item) {
                                  return {
                                      text: item.item_name,                        
                                      id: item.item_id
                                  }
                              })
                          };      
                  },    
                  cache: true,
                },language: {
                    noResults: function() {
                        return "<a  data-toggle='modal' data-target='#myModal' href='javascript:void();'>Open Model</a>";
                      }
                    },escapeMarkup: function (markup) {
                         return markup;
                    }


              });