Dynamically add item to jQuery Select2 control that uses AJAX

前端 未结 9 1570
梦毁少年i
梦毁少年i 2020-11-29 02:44

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



         


        
相关标签:
9条回答
  • 2020-11-29 03:09

    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
        })
    
    0 讨论(0)
  • 2020-11-29 03:11

    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:

    $(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.

    0 讨论(0)
  • 2020-11-29 03:13

    In case of Select2 Version 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'}]});
    
    
    
    //  append option
    $("#select_with_data").append('<option value="5">Twitter</option>');
    $("#select_with_data").val('5');
    $("#select_with_data").trigger('change');
    
    0 讨论(0)
  • 2020-11-29 03:19

    In Select2 4.0.2

    $("#yourId").append("<option value='"+item+"' selected>"+item+"</option>");
    $('#yourId').trigger('change'); 
    
    0 讨论(0)
  • 2020-11-29 03:20

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

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

     $.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>
    
    0 讨论(0)
  • 2020-11-29 03:23

    Extending on Bumptious Q Bangwhistle's answer:

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

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

    0 讨论(0)
提交回复
热议问题