0

I am successfully populating a select2 (v4.0.1) dropdown with dynamically (via AJAX) retrieved options.

Here is the HTML:

<select id="part-reference" class="select-dropdown" name="part-reference"></select>

Here is the Javascript:

$('#part-reference').select2({
        ajax: {
            url: function (params) {
                return "parts/parts-search?nodecorator=true&input=" + params.term;
            },
            dataType: 'json',
            type: "POST",
            delay: 300,
            processResults: function (data, params) {
                return {
                    results: data.results
                };
            },
            cache: true
        }
    });

The AJAX response looks like this:

{
  "results": [
    {
      "id": 2,
      "text": "Two"
    },
    {
      "id": 3,
      "text": "Three"
    }
  ]
}

When I select one of the options in the dropdown the input field is not populated with the text, and when I submit the form the value for this select is undefined.

What do I need to do so that when a dynamically added option is clicked, it populates the input field and sets its value?

crmepham
  • 4,676
  • 19
  • 80
  • 155
  • Could you please make a jsfiddle so that other people quickly check and help? – xadhix Jul 31 '18 at 10:15
  • use `$.map` check this example [link](https://stackoverflow.com/questions/20926707/how-to-use-select2-with-json-via-ajax-request) – Marcogomesr Jul 31 '18 at 10:18
  • Should I need to use `$.map`? I think my data is in the correct format? – crmepham Jul 31 '18 at 10:41
  • You're right you don't need to use a `map` as the format is correct. It seems to work fine: [JSFIDDLE](https://jsfiddle.net/shashank2104/4uzap0Lx/6/) Try using the `targetSelection` option to force print the value (either ID or text) – Shashank Jul 31 '18 at 19:07

0 Answers0