Select2 search box always visible

Sample code showing how a single-select Select2 can be hacked to always show the search box.

by John Pisello

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/js/select2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/css/select2.min.css">
  <select id="search">
    <option value=""></option>
  </select>
  <p id="selection"><i>This is the user's selection:</i> <b>(none)</b></p>

CSS

#search {
  width: 40ch;
}
#selection {
  margin-top: 4rem;
}

JavaScript

$(document).ready(() => {
	const hash = text => {
  	return text.split('').reduce((acc, cur) => {
    	return acc ^ cur.charCodeAt(0);
    }, 0xff);
  };
  const $search = $('#search');
  $search.select2({
    'placeholder': 'Enter search terms',
    'minimumInputLength': 2,
    'ajax': {
      url: 'https://api.github.com/search/repositories',
      data: params => {
        var query = {
          q: params.term + " in:full_name",
          type: 'public'
        }
        return query;
      },
      success: resp => {
      	console.log('response: ', resp);
        $('.select2-results').show();
      },
      processResults: resp => {
      	if (resp.total_count) {
        	let results = resp.items.map(item => ({
      			'id': item.id,
        		'text': item.full_name
      		}));
          console.log('processed results:', results);
          return ({results});
        } else {
        	return [];
        }
      },
      delay: 250
    },
  });
  
  // Prevent the Select2 from closing.
  $search.on('select2:closing', evt => {
    const choice = $search.select2('data');
    console.debug('selection:', choice);
    if (choice && choice.length) {
    	$('#selection > b').text(choice[0].text);
    }
		evt.preventDefault();
   	$('.select2-results').hide();
  });
  
  // Hide the dropdown when the Select2 opens.
  $search.on('select2:open', evt => {
  	$('.select2-selection.select2-selection--single').hide();
  	$('.select2-results').hide();
  });
  
  // Force the Select2 open.
  $search.select2('open');
});