Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 我需要加上一句;添加新项目";选择2中的选项_Jquery_Jquery Select2_Jquery Select2 4 - Fatal编程技术网

Jquery 我需要加上一句;添加新项目";选择2中的选项

Jquery 我需要加上一句;添加新项目";选择2中的选项,jquery,jquery-select2,jquery-select2-4,Jquery,Jquery Select2,Jquery Select2 4,我想在列表的第一个元素中添加一个按钮“添加新项目”。如果用户点击该按钮,我需要打开一个弹出窗口,从用户那里获取输入。 如何在select2插件中执行此操作?是否有此(或)的默认选项需要自定义此选项?您可以通过这种方式向select2添加新选项 $('button').click(function(){ var value = prompt("Please enter the new value"); $(".mySelect") .append($("<option>

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

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

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

})
$(“按钮”)。单击(函数(){
var值=提示(“请输入新值”);
$(“.mySelect”)
.append($(“”)
.attr(“值”,值)
.文本(值));
})

基本上是Kld建议的,但据我所知,OP希望使用
select
的第一个选项来触发新的值模式,因此没有额外的按钮。触发select2:close事件时,它会检查值,如果选择了
“新建”
,则会提示输入新值,并在
选择
框的末尾添加并选择该值

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

$(函数(){
$(“.select2”)
.选择2({
占位符:“选择类型”,
宽度:“50%”,
搜索的最小结果:无穷大
})
.on('select2:close',function(){
var el=$(本);
如果(el.val()=“新建”){
var newval=prompt(“输入新值:”);
如果(newval!==null){
el.追加(“”+newval+“”)
.val(newval);
}
}
});
});

添加新类型
汽车
公共汽车
两个
三

您是否应该使用
标签
选项

jQuery(#select2-“+yourlementId+“-container”).off().on('click',function()){
jQuery(“#yourelementid”_add”).remove();
jQuery(“#select2-”+yourlementId+“-results”)。在(“optionnameforadding”).promise()之后。完成(函数(){
jQuery(“#”+yourelementid+“_add”).off().on('click',function()){
//显示div的功能
});
});
}); 
您可以在ul list-select2-“+yourlementid+”-results之后添加html内容,并对其执行任何操作。只需将结果设置为选择框的val

以下是我的方法

$('#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>');
})
$(“#选择2”)
.select2()
.on('select2:open',()=>{
$(“.select2结果:not(:has(a))”)。追加(“”);
})

在深入研究这个问题一段时间后……我想我找到了解决这个问题的办法

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

所以…在做了一些修改之后,我想出了以下代码:

首先:为DOM中的所有选择创建一个全局绑定。这仅用于设置对当前用户正在使用的“内容”的临时引用--创建一个可供以后使用的全局变量

      $('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:创建一个文档“keyup”事件,该事件映射到Select2临时输入和Select2-search\u字段类。这将捕获Select2输入的所有关键事件。但在本例中,我添加了一个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');
                    }
                })
$(文档).on('keyup','input.select2-search\u field',函数(e){
//捕获返回事件
如果(如keyCode===13){
var newValue=$(this.val();
log('处理此:'+newValue);
//创建新选项元素
var newOpt=$('')
.val(新值)
.文本(新值);
//附加到当前选择项
$(tempSelectedObj)
.append(newOpt);
//应用更改并设置它
$(tempSelectedObj)
.val(新值)
.选择2(“关闭”);
}
})
当检测到返回字符时,会发生以下情况

  • 捕获当前值
  • 创建新的DOM选项元素(jQuery)
  • 设置新选项元素的值和文本
  • 将新的Option元素附加到tempSelectedObj变量(jQuery)
  • 触发Select2关闭
  • 将Select2的值设置为附加的新值
  • 触发最后的Select2更改以显示新选项
  • 完成了
显然,本例需要两部分代码,但我认为对于许多人似乎都在努力解决的问题来说,这是一种非常巧妙的方法。而且它非常通用,可以轻松地为其他目的定制

希望这有帮助!我已经为此奋斗了一段时间

以下是一个工作示例:

$('#my-select2').select2().on('select2:open',function(){
var a=$(this.data('select2');
如果(!$('.select2 link').length){
a、 $results.parents(“.select2 results”)

.append('

试试这个它对我有用

$('#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;
                    }


              });
$('yourDropdownId')。选择2({
阿贾克斯:{
url:productUrl,
数据类型:“json”,
数据:函数(参数){
变量查询={
搜索:params.term,
页码:params.page | | 1
}
//查询参数将是?search=[term]&page=[page]
返回查询;
},processResults:函数(数据,参数){
console.log(数据)
返回{
结果:$.map(数据.items,函数(item){
  $('#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
                        });
      }
   });
$('#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;
                    }


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

});