Select2 Default values for multiple select and allowed tags

前端 未结 3 1358
一整个雨季
一整个雨季 2020-12-16 02:22

I have a select 2 multi-select option


                        
    
提交评论

  • 2020-12-16 02:49

    An other simple way is set value to select option and make it select2 again :

    $('#properties').val(["Trade Fair", "CA", "Party"]);
    $('#properties').select2({});
    

    It is working for me

    Little improvement:

    $('#province').val(["3", "4", "5"]).trigger('change');
    
    0 讨论(0)
  • 2020-12-16 03:11

    Doing a little digging, I can see this issue raised on GitHub.

    One option is to check to see if the value exists, and append it if it doesn't.

    var s2 = $("#selectEvents").select2({
        placeholder: "Choose event type",
        tags: true
    });
    
    var vals = ["Trade Fair", "CA", "Party"];
    
    vals.forEach(function(e){
    if(!s2.find('option:contains(' + e + ')').length) 
      s2.append($('<option>').text(e));
    });
    
    s2.val(vals).trigger("change"); 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css" rel="stylesheet"/>
    
    <select multiple name="event_type[]" class="form-control" id="selectEvents">
      <option>Trade Fair</option>
      <option>Party</option>
      <option>Foo</option>
      <option>Bar</option>
    </select>

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