Search code examples
javascriptphpjqueryajaxjquery-select2

How to set selected value of jQuery Select2?


This belong to codes prior to Select2 version 4

I have a simple code of select2 that get data from AJAX.

$("#programid").select2({
  placeholder: "Select a Program",
  allowClear: true,
  minimumInputLength: 3,
  ajax: {
    url: "ajax.php",
    dataType: 'json',
    quietMillis: 200,
    data: function (term, page) {
      return {
        term: term, //search term
        flag: 'selectprogram',
        page: page // page number
      };
    },
    results: function (data) {
      return {results: data};
    }
  },
  dropdownCssClass: "bigdrop",
  escapeMarkup: function (m) { return m; }
});

This code is working, however, I need to set a value on it as if in edit mode. When user select a value first time, it will be saved and when he needs to edit that value it must appear in the same select menu (select2) to select the value previously selected but I can't find a way.

UPDATE:

The HTML code:

<input type="hidden" name="programid" id="programid" class="width-500 validate[required]">

Select2 programmatic access does not work with this.


Solution

  • To dynamically set the "selected" value of a Select2 component:

    $('#inputID').select2('data', {id: 100, a_key: 'Lorem Ipsum'});
    

    Where the second parameter is an object with expected values.

    UPDATE:

    This does work, just wanted to note that in the new select2, "a_key" is "text" in a standard select2 object. so: {id: 100, text: 'Lorem Ipsum'}

    Example:

    $('#all_contacts').select2('data', {id: '123', text: 'res_data.primary_email'});
    

    Thanks to @NoobishPro