Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't programmatically select option using Select2

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?

like image 482
user3775501 Avatar asked Dec 19 '22 12:12

user3775501


1 Answers

var $example = $(".js-example-programmatic").select2();
$example.val("CA").trigger("change"); 
like image 87
pmeyer Avatar answered Dec 22 '22 00:12

pmeyer