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() {_x000D_
$("#state").select2({_x000D_
tags: true_x000D_
});_x000D_
_x000D_
$("#btn-add-state").on("click", function(){_x000D_
var newStateVal = $("#new-state").val();_x000D_
// Set the value, creating a new option if necessary_x000D_
if ($("#state").find("option[value=" + newStateVal + "]").length) {_x000D_
$("#state").val(newStateVal).trigger("change");_x000D_
} else { _x000D_
// Create the DOM option that is pre-selected by default_x000D_
var newState = new Option(newStateVal, newStateVal, true, true);_x000D_
// Append it to the select_x000D_
$("#state").append(newState).trigger('change');_x000D_
} _x000D_
}); _x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>_x000D_
_x000D_
_x000D_
<select id="state" class="js-example-basic-single" type="text" style="width:90%">_x000D_
<option value="AL">Alabama</option>_x000D_
<option value="WY">Wyoming</option>_x000D_
</select>_x000D_
<br>_x000D_
<br>_x000D_
<input id="new-state" type="text" />_x000D_
<button type="button" id="btn-add-state">Set state value</button>
_x000D_
Hint: try entering existing values into the text box, like "AL" or "WY". Then try adding some new values.