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?
-
I tried below code for select2 jsfiddle.net/KpKaran/rqtuk090 – Prabhakarank Jul 28 '16 at 14:54
-
Another solution: customize noResults with html code stackoverflow.com/questions/37797597/… – markux Dec 28 '17 at 16:03
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>
$('#my-select2').select2().on('select2:open', function () {
var a = $(this).data('select2');
if (!$('.select2-link').length) {
a.$results.parents('.select2-results')
.append('<div class="select2-link"><a>New item</a></div>')
.on('click', function (b) {
a.trigger('close');
// add your code
});
}
});
-
One side-effect is that it adds a new button for each time the dropdown is opened. – Tim Cadieux Dec 20 '19 at 1:43
HTML Code
<div class="input-group">
<select class="form-control select2-hidden-accessible" data-plugin="select2" id='select' tabindex="-1" aria-hidden="true">
<optgroup label="Select Cutomer">
<option value="AK">Zilal</option>
<option value="HI">Ajay</option>
</optgroup>
</select>
<div class="wrapper" id="wrp" style="display: none;">
<a href="#" id="type" class="font-weight-300" data-target="#mdl_Item" data-toggle="modal">+ Add New Vendor</a>
</div>
</div>
JavaScript Code:
$(document).ready(function () {
var flg = 0;
$('#select').on("select2:open", function () {
flg++;
if (flg == 1) {
$this_html = jQuery('#wrp').html();
$(".select2-results").append("<div class='select2-results__option'>" +
$this_html + "</div>");
}
});
});
Output looks like as shown below:
You can add a new option to the select2 this way
$('button').click(function(){
var value = prompt("Please enter the new value");
$(".mySelect")
.append($("<option></option>")
.attr("value", value )
.text(value ));
})
May be you should use tags
options?
https://select2.github.io/options.html#can-options-be-created-based-on-the-search-term
-
1"click on that button i need to open a pop-up" using tags this is not possible... – user2976753 Jul 19 '17 at 12:55
jQuery("#select2-"+yourelementid+"-container").off().on('click',function(){
jQuery("#yourelementid"_add").remove();
jQuery("#select2-"+yourelementid+"-results").after("<div id='"+yourelementid+"_add' >optionnameforadding</div> ").promise().done(function(){
jQuery("#"+yourelementid+"_add").off().on('click',function(){
// yourfunctionfordisplayingdiv
});
});
});
you can add html content after the ul list - select2-"+yourelementid+"-results , and do whatever you can with it. just set the result as the val of the select box
After digging around on this subject for quite some time... I think I have a solution for this problem.
I noticed that Select2 seems to be creating its own structure within the DOM -- irrespective of the Select that you are interacting with. -- This also appears to be completely independent of the Select you may have created elsewhere in the DOM.
So.... After some fiddling around - I came up with the following code:
First: Create a global binding to all Selects in the DOM. This is only for setting a temporary reference to 'what' the current user is working with -- creating a global variable that can be used later.
$('select').select2().on('select2:open', function() {
// set a global reference for the current selected Select
console.log('found this ---> '+$(this).attr('id'));
if (typeof tempSelectedObj === 'undefined') {
tempSelectedObj = null;
}
tempSelectedObj = this;
});
Second: Create a document 'keyup' event that is mapped to the Select2 temporary INPUT and select2-search__field class. This will capture all key events for the Select2 INPUT. But in this case, I have added a keyCode === 13 (return character) to init the magic.
$(document).on('keyup','input.select2-search__field',function (e) {
// capture the return event
if (e.keyCode === 13) {
var newValue = $(this).val();
console.log('processing this: '+newValue);
// create new option element
var newOpt = $('<option>')
.val(newValue)
.text(newValue);
// append to the current Select
$(tempSelectedObj)
.append(newOpt);
// apply the change and set it
$(tempSelectedObj)
.val(newValue)
.select2('close');
}
})
When a return character is detected, the following happens.
- capture the current value
- create a new DOM Option Element (jQuery)
- set the value and text of the new Option Element
- append the new Option Element to the tempSelectedObj variable (jQuery)
- trigger the Select2 to close
- set the value of the Select2 to the new value appended
- trigger the final Select2 change to display the new Option
- DONE!
Obviously the two sections of code are required for this example, but I think it is a pretty slick approach for a problem which a lot of people seem to be struggling with. And it is generic enough that it could be tailored for other purposes with ease.
Hope this helps! I have struggled with this for sometime.
Here is a working example:
A modified version of modped's answer that I used for multi select
$('.select2').select2().on('select2:close', function() {
var el, newOption, newval;
el = $(this);
if (el.val() !== null && el.val()[0] === '') {
el.val(el.val().slice(1));
el.trigger('change');
newval = prompt("Enter new value:");
if (newval !== null && newval !== '') {
newOption = new Option(newval, newval, true, true);
return el.append(newOption).trigger('change');
}
}
});
Show Snippet
$('#select2').select2({
placeholder: 'This is my placeholder',
language: {
noResults: function() {
return `<button style="width: 100%" type="button"
class="btn btn-primary"
onClick='task()'>+ Add New Item</button>
</li>`;
}
},
escapeMarkup: function (markup) {
return markup;
}
});
function task()
{
alert("Hello world! ");
}
.container {
display: flex;
justify-content: center;
align-items: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<br>
<div class="container">
<select id="select2" style="width: 70%">
<option value="">Select</option>
<option value="40">Fairy Floss Machine</option>
<option value="30">Popcorn machine</option>
<option value="20">Bubble Machine</option>
<option value="10">Smoke Machine</option>
<option value="0">party Effect Light</option>
</select>
</div>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
Try this it is working for me
$('#yourDropdownId').select2({
ajax: {
url: productUrl,
dataType: 'json',
data: function (params) {
var query = {
search: params.term,
page: params.page || 1
}
// Query parameters will be ?search=[term]&page=[page]
return query;
},processResults: function (data, params) {
console.log(data)
return {
results: $.map(data.items, function (item) {
return {
text: item.item_name,
id: item.item_id
}
})
};
},
cache: true,
},language: {
noResults: function() {
return "<a data-toggle='modal' data-target='#myModal' href='javascript:void();'>Open Model</a>";
}
},escapeMarkup: function (markup) {
return markup;
}
});