I need to add the option "Add new item" in Select2

I want to add a button in the first element of the list to "Add a new element". If the user clicks on this button, I need to open a popup window and receive data from users. How to do this in select2 plugin? Are there any default options for this (or) need to configure this?

+8
source share
10 answers

in principle, what Kld suggested, but without additional buttons, because I understand that the OP wants to use the first select option to start a new modal value. It checks the value when select2 is triggered: the close event and if "NEW" selected, requests a new value, adds select at the end and selects it.

NOTE. I turned off the search in the input file and added a 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> 
+4
source

Here is 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>'); }) 

enter image description here

+4
source
  $('#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 }); } }); 

enter image description here

+4
source

You can add a new select2 option this way

 $('button').click(function(){ var value = prompt("Please enter the new value"); $(".mySelect") .append($("<option></option>") .attr("value", value ) .text(value )); }) 
+1
source
 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 the html content after the list ul - select2 - "+ yourelementid +" - the results and do whatever you can with it. just set the result as val in the select box

check image

+1
source

After a lot of work on this issue ... I think I have a solution to this problem.

I noticed that Select2 seems to create its own structure inside the DOM - regardless of the choice you interact with. β€œIt is also completely independent of the choices you might have made elsewhere in the DOM.”

So ... After some messing around - I came up with the following code:

First: Create a global binding to all selections in the DOM. This is only for setting a temporary link 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 "keyup" event for the document that appears in Select2 time INPUT and select2-search__field. This will capture all key events for Select2 INPUT. But in this case, I added keyCode === 13 (return character) to start 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 found, the following occurs.

  • capture current value
  • create a new DOM Option element (jQuery)
  • set the value and text of the new Option element
  • add new Option element to tempSelectedObj (jQuery) variable
  • call Select2 to close
  • set the value of Select2 to the new value added
  • triggers a final change to Select2 to display a new option
  • DONE!

Obviously, this example requires two sections of code, but I think this is a pretty attractive approach to a problem that many people seem to struggle with. And this is common enough that it could be easily adapted for other purposes.

Hope this helps! I struggled with this for a while.

Here is a working example:

https://jsfiddle.net/h690bkmg/1/

0
source

Try it, it works 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; } }); 
0
source

A modified version of the mod answer that I used for multiple selection

 $('.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'); } } }); 
0
source

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>"); } }); 

The output looks like the one below:

enter image description here

0
source

All Articles