I need to update an array data source. Using the reset/clear technique from https://stackoverflow.com/a/28271338/161457 does not clear the options; the control combines them (one, two, three, four in the code snippet). How can I clear the control and reinitialize the options?
$(function () {
var initialData = [{ id: 1, text: 'one' }, { id: 2, text: 'two' }];
$("#test").select2({
data: initialData
});
$('#change').click(function () {
var newData = [{ id: 3, text: 'three' }, { id: 4, text: 'four' }];
$('#test').val([]); // Attempt to clear
$("#test").select2({
data: newData
});
});
});
@import url('https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css');
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<form>
<select id="test" name="test" multiple="multiple" style="width: 50%"></select>
</form>
<button type="button" id="change">Change</button>