Select2 4.x Preload AJAX option with extra data fields

19 views Asked by At

I'm migrating from Select2 3.5.x. I have a lot of instances where I just the ajax option to get data that is more than just {id, text}. In 4.x, I am getting the ajax calls working well. However I can't get the pre-loaded data from page load to work. Since initSelection is deprecated, I can't seem to figure out how to use a dataAdapter (documentation feels a bit lacking to me).

HTML:

<select name="item" id="myselect">
  <option selected="selected" 
      value="bross" 
      data-email="[email protected]" 
      data-phone="888-555-12345">Bob Ross</option>
</select>

JS:

$("#myselect").select2({
    ajax: {
        type: 'POST',
        url: "getemployee.cshtml",
        dataType: 'json',
        data: function (params) {
            return {
                tern: params.term // search term
            };
        },
        processResults: function (data, params) {
            return { results: data };
        }
    }
 
});

If I run $("#myselect").select2('data')[0] in console after page load I get:

{
    "selected": true,
    "disabled": false,
    "text": "Bob Ross",
    "id": "bross",
    "title": "",
    "_resultId": "select2-item-em-result-w1un-bross",
    "element": {}
}

However if I run the same thing after I type/search/ajax a result (and sever gives me json with all the data), it gives me the data I want:

{
    "selected": false,
    "disabled": false,
    "text": "Bob Ross",
    "id": "bross",
    "email": "[email protected]",
    "phone": "888-555-12345"
    "_resultId": "select2-item-7x-result-iew4-bross",
    "element": {}
}

How can I get it to initially load in the ancillary data fields in a semi-graceful way?

0

There are 0 answers