I want to add a button in first element of the list to "Add new item". If user clicks on that button I need to open a pop-up and get the input from users. How to do this in select2 plugin? Is any default options for this (or) need to customize this?
New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data.text, data.id, false, false); $('#mySelect2').append(newOption).trigger('change');
HTML. Create a <select class="select2_el" > element to initialize select2 on page load and create <div id="elements" > container to store <select > element on button click using jQuery AJAX.
Select2 does not function properly when I use it inside a Bootstrap modal. This issue occurs because Bootstrap modals tend to steal focus from other elements outside of the modal. Since by default, Select2 attaches the dropdown menu to the <body> element, it is considered "outside of the modal".
In the past, Select2 required an option called initSelection that was defined whenever a custom data source was being used, allowing for the initial selection for the component to be determined. This has been replaced by the current method on the data adapter. AMD Modules: select2/compat/initSelection"
Here's my approach
$('#select2')
.select2()
.on('select2:open', () => {
$(".select2-results:not(:has(a))").append('<a href="#" style="padding: 6px;height: 20px;display: inline-table;">Create new item</a>');
})
basically what Kld suggested, but without additional buttons as I understand OP wants to use first option of select
to trigger new value modal. It checks the value when select2:close event is triggered and if "NEW"
is selected, prompts for new value, adds at the end of select
box and selects it.
NOTE: I've disabled search in input and added placeholder
$(function () {
$(".select2")
.select2({
placeholder: 'Select type',
width: '50%',
minimumResultsForSearch: Infinity
})
.on('select2:close', function() {
var el = $(this);
if(el.val()==="NEW") {
var newval = prompt("Enter new value: ");
if(newval !== null) {
el.append('<option>'+newval+'</option>')
.val(newval);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select id="mySel" class="select2">
<option></option>
<option value="NEW">Add new type</option>
<option>Car</option>
<option>BUS</option>
<option>TWO</option>
<option>THREE</option>
</select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With