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.
- Use
.select2("val", value). Does nothing. - Use
.select2("data", value). Does nothing. Not sure how this is supposed to be different. - Use the
InitSelectionoption 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?
.select2("val", value)works for me. Could you provide a minimal complete reprodution?$('#hidDishID').val = data.DishID;This looks wrong. Could you try chaning it to$('#hidDishID').val(data.DishID);please?@Html.DropDownGroupListFor()takes place purely on the server. They don't do binding, at least not in the same context. They shouldn't be able to interact. It's purely one way communication. Select2 is only invoked after the server-side processing is completely done.