Skip to main content
Blog

Searchable dropdowns with Select2 and Bootstrap

By 4 december 2015januari 30th, 2017No Comments

Select2 is a plugin for HTML dropdowns built with jQuery. Select2 makes it possible to search the options in the dropdown, which comes in handy when there are a lot of options in the dropdown. There is also support for Bootstrap available, so integration with Bootstrap works need as well.

select2_loaded_open

In order to add Select2 to your dropdown you need to include:

<html><head>
<!– Bootstrap –>
<link rel="stylesheet" href="bootstrap.min.css">
<!– select2 –>
<link href="select2.css" rel="stylesheet"/>
<link href="select2-bootstrap.css" rel="stylesheet"/>
<script src="jquery.min.js"></script>
<script src="bootstrap.min.js"></script>
<script src="select2.full.js"></script>
<!– There is also a minified version of this –>
</head><body></body></html>

and add the classes ‘select2’ and ‘select2-hidden-accessible’.

HTML:

<select id="select2-dropdown" class="select2 select2-hidden-accessible" aria-hidden="true">
    <option selected disabled hidden value=""></option>
    <option value="yellow">yellow</option>
    <option value="orange">oranje</option>
    <option value="red">red</option>
    <option value="blue">blue</option>
    <option value="green">green</option>
</select>

 

In JavaScript you can call the select2() function and pass in the options (see documentation for a list of options [3]):

$.fn.select2.defaults.set("theme", "bootstrap"); // tells select2 to use Bootstrap theme
$('#select2-dropdown').select2(
      {
          placeholder: 'Selecteer een kleur…',
          allowClear: true,
          language: "nl",
          width: null
      }
);

 

The result of this will look like this:

select2_loaded_closed

 

select2_loaded_open

 

select2_loaded_search

 

To update the options: 

$('#update-colors').on('click', function () {
    $('#select2-dropdown').append('<option value="purple">purple</option>');
    $('#select2-dropdown').append('<option value="brown">brown</option>');
    $('#select2-dropdown').select2('destroy'); //destroy the old select2
    addSelect2(); // add select2 a new
});

Here we are adding two options: purple and brown. Now after clicking the update button the result is:

select2_updated_open

 

select2_updated_search

 

 

 

It is also possible to use ajax calls with select2. To find out more about this, take a look at the documentation [5].   Read more

  1. https://select2.github.io/
  2. https://select2.github.io/examples.html
  3. https://select2.github.io/options.html
  4. https://fk.github.io/select2-bootstrap-css/
  5. https://select2.github.io/examples.html#data-ajax