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.
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:
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:
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