Can't programmatically select option using Select2

霸气de小男生 提交于 2019-12-23 13:39:10

问题


I have a Select2 working fine attached to a select list but when someone enters a new item and I rebind the select list and try to programmatically select the new item, it refuses to display.
There are a number of other posts re this but their solutions don't work for me.

  1. Use .select2("val", value). Does nothing.
  2. Use .select2("data", value). Does nothing. Not sure how this is supposed to be different.
  3. Use the InitSelection option to set a value. This leads to the following error message: Uncaught Error: Option 'initSelection' is not allowed for Select2 when attached to a select element.

In the Ajax success function after adding the new option to the database, I have the following Javascript:

BindDishes(RestaurantID); //rebinds the select list successfully
$('#hidDishID').val = data.DishID; //populates a hidden field
var arr = '[{id: "' + data.DishID + '", text: "' + data.DishName + '"}]'; 
$("#dd").select2("data", arr);

So in this latest iteration I have tried to supply an array with the id and text from the select list item as per another suggested solution but still nothing occurs. What am I doing wrong? Is this impossible when using Select2 with a select list?

Edit: I have the following line in MVC that creates the Select list:

@Html.DropDownGroupListFor(m => m.DishID, Model.GroupedSelectList, "Select a dish", new { id="dd",style="width:470px;" })

which must be causing the problem by binding to DishID from the model which was originally blank when it came from the server. DropDownGroupListFor is just an HTML helper that allows for using OptionGroups in a Select but it must be the binding that is a problem. What is the best approach here, to bind in a different way or to somehow update the model's DishID, not sure of the best practice?


回答1:


var $example = $(".js-example-programmatic").select2();
$example.val("CA").trigger("change"); 



回答2:


You need to destroy your select2 before adding/modifying items. If you do, then your select2 will respond just like its bound first time

Select2 Dropdown Dynamically Add, Remove and Refresh Items from



来源:https://stackoverflow.com/questions/25128770/cant-programmatically-select-option-using-select2

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