动态地向使用AJAX的jQuery Select2控件添加项

时间:2022-11-27 19:32:15

I have a jQuery Select2 control that uses AJAX to populate:

我有一个jQuery Select2控件,它使用AJAX填充:

<input type="text" name="select2" id="select2" style='width:400px' value="999">

var initialSelection = { id: '999', text:"Some initial option"};

$("#select2").select2({
    placeholder: "Select Option",
    minimumInputLength: 2,
    ajax: { 
        url: "/servletToGetMyData",
        dataType: 'json',
        data: function (term, page) { return { term: term }; },
        results: function (data, page) {  return { results: data.results} }
    },
    initSelection : function(element, callback){ callback(initialSelection); },     
    escapeMarkup: function (m) { return m; }
}); 

The AJAX links to a database of possible options and as you can see requires two characters of input.

AJAX链接到一个可能选项的数据库,如您所见,需要输入两个字符。

The problem is the user can use a dialog to add a new option if the option doesn't exist in the database. Upon return from that dialog, I try:

问题是,如果该选项在数据库中不存在,用户可以使用对话框添加新选项。从那个对话中回来后,我试着:

var o = $("<option/>", {value: newID, text: newText});
$('#select2').append(o);
$('#select2 option[value="' + newID + '"]').prop('selected',true);
$('#select2').trigger('change');

But it doesn't work. The same exact code works for non-AJAX Select2 boxes. I've tried various alternatives, like using $('#select2').select2("val", newID); but it doesn't work.

但它不工作。同样的代码适用于非ajax的Select2框。我尝试过各种替代方法,比如使用$('#select2')。select2(“val”,newID);但它不工作。

I've even tried completely deleting the Select2 control. However, $('#select2').remove() only removes the original <input> field but leaves the Select2 control lingering around. Note that the page has more than one Select2 control, so I can't use a class selector for Select2 controls as it will remove other controls that I need.

我甚至尝试过完全删除Select2控件。但是,$('#select2').remove()只删除原始的字段,而保留select2控件。请注意,该页面有多个Select2控件,因此我不能为Select2控件使用类选择器,因为它将删除我需要的其他控件。

Any idea how to either a) dynamically add an option to a Select2 control that uses AJAX; or b) completely delete a Select2 control so that it can be programmatically added back? Or any other solution...

任何关于如何a)动态地向使用AJAX的Select2控件添加选项的想法;或者b)完全删除Select2控件,以便以编程方式将其添加回来?或任何其他解决方案…

Edit I found another question that shows how to remove a select2 element, using .select2("destroy"). This works but is, in my opinion, sub-optimal. I would much prefer to be able to just add the option than to destroy and re-create the select2.

我发现了另一个问题,它显示了如何使用.select2(“destroy”)删除select2元素。这是可行的,但在我看来是次优的。我更希望能够添加选项,而不是销毁并重新创建select2。

8 个解决方案

#1


32  

This is a lot easier to do starting in select2 v4. You can create a new Option, and append it to the select element directly. See my codepen or the example below:

这在select2 v4中更容易实现。您可以创建一个新选项,并将其直接附加到select元素。参见我的代码页或下面的示例:

$(document).ready(function() {
    $("#state").select2({
      tags: true
    });
      
    $("#btn-add-state").on("click", function(){
      var newStateVal = $("#new-state").val();
      // Set the value, creating a new option if necessary
      if ($("#state").find("option[value=" + newStateVal + "]").length) {
        $("#state").val(newStateVal).trigger("change");
      } else { 
        // Create the DOM option that is pre-selected by default
        var newState = new Option(newStateVal, newStateVal, true, true);
        // Append it to the select
        $("#state").append(newState).trigger('change');
      } 
    });  
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>


<select id="state" class="js-example-basic-single" type="text" style="width:90%">
  <option value="AL">Alabama</option>
  <option value="WY">Wyoming</option>
</select>
<br>
<br>
<input id="new-state" type="text" />
<button type="button" id="btn-add-state">Set state value</button>

Hint: try entering existing values into the text box, like "AL" or "WY". Then try adding some new values.

提示:尝试将现有值输入文本框,如“AL”或“WY”。然后尝试添加一些新的值。

#2


26  

This provided a simple solution: Set data in Select2 after insert with AJAX

这提供了一个简单的解决方案:在使用AJAX插入之后在Select2中设置数据

$("#select2").select2('data', {id: newID, text: newText});      

#3


14  

In case of Select2 Version 4+

如果选择2版本4+

it has changed syntax and you need to write like this:

它改变了语法,你需要这样写:

// clear all option
$('#select_with_blank_data').html('').select2({data: [{id: '', text: ''}]});

// clear and add new option
$("#select_with_data").html('').select2({data: [
 {id: '', text: ''},
 {id: '1', text: 'Facebook'},
 {id: '2', text: 'Youtube'},
 {id: '3', text: 'Instagram'},
 {id: '4', text: 'Pinterest'}]});

#4


11  

In Select2 4.0.2

在Select2 4.0.2

$("#yourId").append("<option value='"+item+"' selected>"+item+"</option>");
$('#yourId').trigger('change'); 

#5


9  

I have resolved issue with the help of this link http://www.bootply.com/122726. hopefully will help you

在这个链接http://www.bootply.com/122726的帮助下,我解决了这个问题。希望能帮助你

Add option in select2 jquery and bind your ajax call with created link id(#addNew) for new option from backend. and the code

在select2 jquery中添加选项,并使用创建的链接id(#addNew)从后端绑定ajax调用。和代码

 $.getScript('http://ivaynberg.github.io/select2/select2-3.4.5/select2.js',function(){

  $("#mySel").select2({
    width:'240px',
    allowClear:true,
    formatNoMatches: function(term) {
        /* customize the no matches output */
        return "<input class='form-control' id='newTerm' value='"+term+"'><a href='#' id='addNew' class='btn btn-default'>Create</a>"
    }
  })
  .parent().find('.select2-with-searchbox').on('click','#addNew',function(){
    /* add the new term */
    var newTerm = $('#newTerm').val();
    //alert('adding:'+newTerm);
    $('<option>'+newTerm+'</option>').appendTo('#mySel');
    $('#mySel').select2('val',newTerm); // select the new term
    $("#mySel").select2('close');       // close the dropdown
  })

});



<div class="container">
    <h3>Select2 - Add new term when no search matches</h3>
    <select id="mySel">
        <option>One</option>
        <option>Two</option>
        <option>Three</option>
        <option>Four</option>
        <option>Five</option>
        <option>Six</option>
        <option>Twenty Four</option>
    </select>
    <br>
    <br>
</div>

#6


5  

Extending on Bumptious Q Bangwhistle's answer:

延伸到傲慢的Q Bangwhistle的回答:

$('#select2').append($('<option>', { 
    value: item,
    text : item 
})).select2();

This would add the new options into the <select> tags and lets select2 re-render it.

这将在

#7


1  

$("#my_select").select2('destroy').empty().select2({data: [{id: 1, text: "new_item"}]});

#8


1  

I did it this way and it worked for me like a charm.

我是这样做的,它对我来说就像一种魅力。

var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, 

    text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];

    $(".js-example-data-array").select2({
      data: data
    })

#1


32  

This is a lot easier to do starting in select2 v4. You can create a new Option, and append it to the select element directly. See my codepen or the example below:

这在select2 v4中更容易实现。您可以创建一个新选项,并将其直接附加到select元素。参见我的代码页或下面的示例:

$(document).ready(function() {
    $("#state").select2({
      tags: true
    });
      
    $("#btn-add-state").on("click", function(){
      var newStateVal = $("#new-state").val();
      // Set the value, creating a new option if necessary
      if ($("#state").find("option[value=" + newStateVal + "]").length) {
        $("#state").val(newStateVal).trigger("change");
      } else { 
        // Create the DOM option that is pre-selected by default
        var newState = new Option(newStateVal, newStateVal, true, true);
        // Append it to the select
        $("#state").append(newState).trigger('change');
      } 
    });  
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>


<select id="state" class="js-example-basic-single" type="text" style="width:90%">
  <option value="AL">Alabama</option>
  <option value="WY">Wyoming</option>
</select>
<br>
<br>
<input id="new-state" type="text" />
<button type="button" id="btn-add-state">Set state value</button>

Hint: try entering existing values into the text box, like "AL" or "WY". Then try adding some new values.

提示:尝试将现有值输入文本框,如“AL”或“WY”。然后尝试添加一些新的值。

#2


26  

This provided a simple solution: Set data in Select2 after insert with AJAX

这提供了一个简单的解决方案:在使用AJAX插入之后在Select2中设置数据

$("#select2").select2('data', {id: newID, text: newText});      

#3


14  

In case of Select2 Version 4+

如果选择2版本4+

it has changed syntax and you need to write like this:

它改变了语法,你需要这样写:

// clear all option
$('#select_with_blank_data').html('').select2({data: [{id: '', text: ''}]});

// clear and add new option
$("#select_with_data").html('').select2({data: [
 {id: '', text: ''},
 {id: '1', text: 'Facebook'},
 {id: '2', text: 'Youtube'},
 {id: '3', text: 'Instagram'},
 {id: '4', text: 'Pinterest'}]});

#4


11  

In Select2 4.0.2

在Select2 4.0.2

$("#yourId").append("<option value='"+item+"' selected>"+item+"</option>");
$('#yourId').trigger('change'); 

#5


9  

I have resolved issue with the help of this link http://www.bootply.com/122726. hopefully will help you

在这个链接http://www.bootply.com/122726的帮助下,我解决了这个问题。希望能帮助你

Add option in select2 jquery and bind your ajax call with created link id(#addNew) for new option from backend. and the code

在select2 jquery中添加选项,并使用创建的链接id(#addNew)从后端绑定ajax调用。和代码

 $.getScript('http://ivaynberg.github.io/select2/select2-3.4.5/select2.js',function(){

  $("#mySel").select2({
    width:'240px',
    allowClear:true,
    formatNoMatches: function(term) {
        /* customize the no matches output */
        return "<input class='form-control' id='newTerm' value='"+term+"'><a href='#' id='addNew' class='btn btn-default'>Create</a>"
    }
  })
  .parent().find('.select2-with-searchbox').on('click','#addNew',function(){
    /* add the new term */
    var newTerm = $('#newTerm').val();
    //alert('adding:'+newTerm);
    $('<option>'+newTerm+'</option>').appendTo('#mySel');
    $('#mySel').select2('val',newTerm); // select the new term
    $("#mySel").select2('close');       // close the dropdown
  })

});



<div class="container">
    <h3>Select2 - Add new term when no search matches</h3>
    <select id="mySel">
        <option>One</option>
        <option>Two</option>
        <option>Three</option>
        <option>Four</option>
        <option>Five</option>
        <option>Six</option>
        <option>Twenty Four</option>
    </select>
    <br>
    <br>
</div>

#6


5  

Extending on Bumptious Q Bangwhistle's answer:

延伸到傲慢的Q Bangwhistle的回答:

$('#select2').append($('<option>', { 
    value: item,
    text : item 
})).select2();

This would add the new options into the <select> tags and lets select2 re-render it.

这将在

#7


1  

$("#my_select").select2('destroy').empty().select2({data: [{id: 1, text: "new_item"}]});

#8


1  

I did it this way and it worked for me like a charm.

我是这样做的,它对我来说就像一种魅力。

var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, 

    text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];

    $(".js-example-data-array").select2({
      data: data
    })