Predefined options for Select2 control using remote data source
Example for article at https://www.gyrocode.com/articles/predefined-options-for-select2-control-using-remote-data-source
by gyrocode
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<script src="https://cdn.staticaly.com/gist/mpryvkin/49dafa457b9f0072b07a974969a94a27/raw/6316f8f0367ef7c4b036b9d8b465e94b95986efe/select2_extended_ajax_adapter.js"></script>
<h3><a href="">Predefined options for Select2 control using remote data source</a>: Show selected option</h3>
<select id="example" style="width:50%">
<option></option>
<option value="PA" selected>Pennsylvania</option>
<option value="PA">Pennsylvania</option>
<option value="VA">Virginia</option>
</select>
<hr><a href="https://www.gyrocode.com/articles/" target="_blank">See more articles</a> on <a href="https://www.gyrocode.com/articles/" target="_blank">Gyrocode.com</a>
CSS
body { background-color: #F4F4F4; }
JavaScript
$(document).ready(function () {
// Get Select2 control
var $select2 = $('#example');
// Get options with "value" attributes that are not selected by default
var $defaultResults = $('option[value]:not([selected])', $select2);
var defaultResults = [];
$defaultResults.each(function () {
var $option = $(this);
defaultResults.push({
id: $option.attr('value'),
text: $option.text()
});
});
// Initialize Select2 control
$select2.select2({
placeholder: 'State',
minimumInputLength: 2,
ajax: {
delay: 250,
url: 'https://gyrocode.com//lab/articles/predefined-options-for-select2-control-using-remote-data-source/states.php'
},
dataAdapter: $.fn.select2.amd.require('select2/data/extended-ajax'),
defaultResults: defaultResults
});
});