0

The Method from docs works well only for static select. I'm talking about the code

$('#my-select').val(id).trigger('change');

But this code doesn't work properly when I have no static options. All the data I get from ajax response. I'm trying to add default option into the DOM, select by .val(id) and trigger it by .trigger('change') but label of select2 span is empty. It changes if I reinit select2 for this select, but then widget lose ajax support.

Demo

Luciuz
  • 1,637
  • 5
  • 14
  • 15
  • Possible duplicate of [Dynamically add item to jQuery Select2 control that uses AJAX](http://stackoverflow.com/questions/25428361/dynamically-add-item-to-jquery-select2-control-that-uses-ajax) – alexw Apr 08 '16 at 02:11
  • See my answer to this question: http://stackoverflow.com/questions/25428361/dynamically-add-item-to-jquery-select2-control-that-uses-ajax/35386009#35386009, and my codepen: http://codepen.io/alexweissman/pen/zremOV – alexw Apr 08 '16 at 02:12
  • Check this http://codepen.io/anon/pen/xVpYvB – Luciuz Apr 08 '16 at 07:52

1 Answers1

1

Just add the option and place the label. Here is a creepy work solution:

var $select2 = $('#select2');
var newState = new Option(val_text, val_id, true, true);
$select2.empty().append(newState).trigger('change');
$('#select2-'+$select2.attr('id')+'-container').text(val_text);
Luciuz
  • 1,637
  • 5
  • 14
  • 15