select2: Unable to Add Data Attribute for Custom Value with Tag

When I manually add an option to the select, I need to include a custom data attribute. How is that done? When I use AJAX to get the items, this works fine:

processResults: function (data) {
    return {
        results: $.map(data, function (obj) {
            return { 
                id: obj.Id, 
                text: obj.LastName + ', ' + obj.FirstName, 
                company: obj.Company 
            };
        })
    };
}

But I need to load these results back into the select2 as tags upon load and I can’t get the extra data property (company) added:

$.each(dtlPatients, function (index, patient) {
    $('#PatientListControl').select2().append('<option value="' + patient.Id 
           + '" data-company="' + patient.Company + '">' + patient.Name + '</option>');
});

$('#PatientListControl').val(selpatlist).trigger('change');

Am I adding the data attribute properly? Is there a better way to manually add the tags to my select2?

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 5
  • Comments: 16 (6 by maintainers)

Most upvoted comments

4877 doesn’t help at all. The links provided in the thread are just redirects to the new documentation (Configuration page). I’ll see if I can manually set the data attribute after creating the option and see if it’s available afterwards. My question is, is that the correct way to storing that custom bit of data? When I create a tag via the ajax call, how is that stored on the option? Is it a data-* attribute?