Kieveli Kieveli - 8 days ago 4
jQuery Question

How to replace options in a Select2 select box

I'm trying to dynamically clear a Select2 option list, and reload it with new data. Everything I read tells me that I can set the data like I'm doing, but it only appends data, and doesn't clear it.



$("#optioner").select2();

$("#doit").click(function() {
$("#optioner").select2({
data: [{
id: "real1",
text: "Real 1"
}, {
id: "real2",
text: "Real 2"
}]
});
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>

<h1>Demo</h1>

<select id="optioner" class="select2">
<option value="fake1">Fake 1</option>
<option value="fake2">Fake 2</option>
</select>

<input id="doit" type="button" value="Real It Up">





I fiddled that up for yall.

Answer

Select2 doesn't provide a way to totally clear the options before adding them with the data option, simply because it can already be done with jQuery .empty() function.

$("#optioner").empty()
    .select2({ data: /* ... */ });

From issue #3877:

This is the intended behavior of the data option. When Select2 is initialized with data, it converts the array of data objects into <option> elements that it can use.

So when you reinitialize it, it creates a second set of <option> elements.

If not, how do I re-populate the list of options / data for Select2?

You can clear out the existing options by calling .empty() on your original select.

$("select").empty(); 

Note that this will reset any existing selections

$("#optioner").select2();

$("#doit").click(function() {
  var $elem = $("#optioner");
  $elem.empty()
    .select2({
      data: [{
        id: "real1",
        text: "Real 1"
      }, {
        id: "real2",
        text: "Real 2"
      }]
    });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>

<h1>Demo</h1>

<select id="optioner" class="select2">
  <option value="fake1">Fake 1</option>
  <option value="fake2">Fake 2</option>
</select>

<input id="doit" type="button" value="Real It Up">