Select2 is a JavaScript library. It is a jQuery replacement for select boxes. It has two main files, and they are select2.css
and select2.js
Although this is not suggested by the Select2 official site, manual install might something be usual.
select2.min.css
to your project CSS directoryselect2.min.js
to your project JavaScript directory. There is another file call select2.full.min.js. If you would like to use the additional features, you could use this file instead of select2.min.js.
Code in Grails GSP
. Assume we passed an map mapAnimalSelection = [a:“ardwolf”, b:“bat”, c:“cat”, d:“dog”], and selectedAnimal = “c” to the GSP.
<label for="animal">Animal:</label> <select required="required" class="form-control" name="animal" id="animal"> <g:each in="${mapAnimalSelection}"> <option value="${it.key}" <g:if test="${it.key == selectedAnimal}">"selected"</g:if>>${it.value}</option> </g:each> </select>
Code in JavaScript
:
var inputAnimal = $("#animal"); inputAnimal.select2({placeholder: "Please select an animal", dropdownAutoWidth: true});
Once selected an option, the above example will not allow use to clean up the selection. In order to allow use to clear an option, add allowClear: true
in Select2 option.
var inputAnimal = $("#animal"); inputAnimal.select2({placeholder: "Please select an animal", allowClear: true, dropdownAutoWidth: true});
Add “multiple=“multiple”
in the HTML select tag.
<label for="animal">Animal:</label> <select required="required" class="form-control" name="animal" id="animal" multiple="multiple> <g:each in="${mapAnimalSelection}"> <option value="${it.key}" <g:if test="${it.key == selectedAnimal}">"selected"</g:if>>${it.value}</option> </g:each> </select>
Add tags: true
in Select2 JS option
var inputAnimal = $("#animal"); inputAnimal.select2({placeholder: "Please select an animal", tags: true, dropdownAutoWidth: true});
additional options can be found in this page: https://select2.org/configuration/options-api
First do the step 6 listed in the above Manual Install section. Then add the following line before using Select2 to change its default theme to BootStrap one.
$.fn.select2.defaults.set("theme", "bootstrap");
If you experience something strange with the width, and do not want to set it to 100% every time, you can do:
$.fn.select2.defaults.set("width", "100%");