Select2 Dropdown Dynamically Add, Remove and Refresh Items from

我与影子孤独终老i 提交于 2019-12-03 05:05:34

From your example I can see that you attached Select2 plugin to hidden element. In addition you use Ajax call to populate results, so in this case if you need to add a new option to the list you simple call:

$('#valueg').select2('val', 'YOUR_VALUE');

In case of using select element as a container the only way that I found is to reinitialize plugin with new options... Something like this:

var el = $('select[name="type"]', '#details-form');
var temp = el.select2('val'); // save current value
temp.push(NEW_VALUE); // append new one
var newOptions = '<option value="1">1</option><option value="2">2</option>';
el.select2('destroy').html(newOptions ).select2().select2('val', temp);
Veeru

I had the same issue. This is how i solved it

This has nothing to do with select2, manipulating the itself seems to work for me

 $("#lstService").empty();
  for(var i=0;i<data.length;i++){
     $("#lstService").append('<option value="'+data[i].service_id+'">'+data[i].service_name+'</option>');
 }

I did it this way:

var $select2 = $('#valueg').select2(); // getting the select2
var item = 'xyz'; // item to be added
$select2.val(function(i, val) { // val can take function as parameter
  val = val || []; // if value is null init val as an array
  val.push(item); // add the new item
  return val;
}).trigger("change"); //refresh

Hope that helps

It is too late... but this is my solution for people that still have this problem:

html = "";
jQuery("#select_2 option").each(function()
{
    html += '<option value="'+jQuery(this).attr("value")+'">'+jQuery(this).text()+'</option>';
});
html += '<option  value="NEWVALUE">NEW OPTION</option>';
jQuery("#select_2").html(html);
Forer

In my case, the key thing to add after manipulating the underlying select is:

$selectlist.trigger("change"); //$selectlist is the underlying select element.

Select2 works around the change event on a select, so calling "change" updates the option displayed in the select 2.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!