Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
743 views
in Technique[技术] by (71.8m points)

javascript - Select2 Default values for multiple select and allowed tags

I have a select 2 multi-select option

<select multiple name="event_type[]" class="form-control" id="selectEvents">
   @foreach ($eTypes as $type)
       <option>{{$type}}</option>
   @endforeach
</select>

I want to set some default values just in case the user is editing the form. I have successfully done that by doing this

var s2 = $("#selectEvents").select2({
    placeholder: "Choose event type",
    tags: true
});

s2.val(["Trade Fair", "CA", "Party"]).trigger("change"); //CA doesn't show as a default

But the problem is i am allowing user generated options using the tags: true option for select2.

When I set a default value that was initially in the html options it works, but when I set a default that was user generated it doesn't work.

It is my first time using select2.

How can i achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...