Home > Mobile >  Attach AJAX fetched value with Select2
Attach AJAX fetched value with Select2

Time:12-25

I am trying to attach AJAX fetched value with enter image description here

If I click on any value, it is not set to the select box. Values are not working.

CodePudding user response:

Select2 requires that each option has an id property and a text property. In the code above the processResults method is returning an array of objects which contain only a text property, without an id. When adding objects to the array in processResults an id should be included:

options.push({ id: id, text: text });

Details on this format can be found at https://select2.org/data-sources/formats. As per this page:

Blank ids or an id with a value of 0 are not permitted.

You could either use text as the id value if it's unique, or use index 1 ( 1 to avoid a value of 0). In the below example code text is used.

processResults: function(data) {
  var options = [];
  if (data) {
    $.each(data, function (index, text) {
      options.push({ id: text, text: text });
    });
  }
  return {
    results: options
  };
}
  • Related