I'm using the jQuery plugin select2 (V4) and I am calling it on all my selects such as:
var select2_params = {
minimumResultsForSearch: Infinity,
templateResult: applyCategoryClasses,
templateSelection: applyCategoryClasses,
};
$('select').select2(select2_params);
However, on certain selects I would like to add extra options, if for example they are inside a certain parent element.
Is this possible or would I have to destroy the respective select elements and then apply them again with the new options such as:
$('myParent').find('select').select2('destroy');
$('#myParent').find('select').select2({...});
Destroy the select
and then reinitialize it with new parameters (also you can perform so called "chaining"):
jQuery('#element').find('select').select2('destroy').find('select').select2({/*your new parameters*/});
You can also define your configuration options by using the HTML5 data-*
attributes, which will override any options set when initializing Select2
and any defaults.
<select data-tags="true" data-placeholder="Select an option" data-allow-clear="true"></select>
The above code is equivalent to:
jQuery("select").select2({
tags: "true",
placeholder: "Select an option",
allowClear: true
});