How to set default value on an input box with select2 initialized on it?

You need to utilize the initSelection method as described in Select2's documentation.

From the documentation:

Called when Select2 is created to allow the user to initialize the selection based on the value of the element select2 is attached to.

In your case, take a look at the Loading Remote Data example as it shows how to incorporate it along with AJAX requests.

I hope this helps.


The method initSelection can not have an empty value attribute to work properly.

That was my problem.

Hopefully this will help someone.


Old initial selections with initSelection

In the past, Select2 required an option called initSelection that was defined whenever a custom data source was being used, allowing for the initial selection for the component to be determined. This has been replaced by the current method on the data adapter.

{
  initSelection : function (element, callback) {
    var data = [];
    $(element.val()).each(function () {
      data.push({id: this, text: this});
    });
    callback(data);
  }
}

You can use the set value too.

You should directly call .val on the underlying element instead. If you needed the second parameter (triggerChange), you should also call .trigger("change") on the element.

$("select").val("1").trigger("change"); // instead of $("select").select2("val", "1");

Refs:

  • https://select2.github.io/announcements-4.0.html
  • https://github.com/select2/select2/issues/2086
  • http://jsfiddle.net/F46NA/7/

If you have an input element, declare it as follows. Remember to populate the value field as well.

<input type="hidden" name="player" id="player" data-init-text="bla bla" value="bla bla" >

Write an initSelection function

 initSelection : function (element, callback) {
                    var elementText = $(element).attr('data-init-text');
                    callback({"text":elementText,"id":elementText});
            }

make sure that this call back has same key value pair as the one return by the ajax call.

callback({"text":elementText,"id":elementText});

I have noticed that keeping the value field empty will keep the input empty by default so remember to populate it as well.