How to set source data array with data attribute & selected?


#1

Hi

01 I want to set data attributes in json data. I am fetching data on page load and passing to select2
here is the code and how to select the default value. I am using 4.0.5 Version. Please help me I am new to select2.

02 If I used Ajax option in select2 it works when use click on select control. How can I preload it with data. As date is same not going to change and hardly few so Its better for me to fetched it once not every time use click on control.

var mydata = [
{ “id” = : 1, “text” : “AAA”, “data-mobile” : “1234”},
{ “id” = : 2, “text” : “BBB”, “data-mobile” : “2345”},
{ “id” = : 3, “text” : “CCC”, “data-mobile” : “3456”},
{ “id” = : 4, “text” : “DDD”, “data-mobile” : “4567”},
{ “id” = : 5, “text” : “EEE”, “data-mobile” : “5678”}
];

$(’#example-data’).select2({
placeholder: ‘Select a month’,
data : mydata
});

// ***************** Expecting output ************

<option value=“1” “data-mobile” = “1234” >AAA
<option value=“2” “data-mobile” = “2345”>BBB
<option value=“3” “data-mobile” = “3456”>CCC
<option value=“4” “data-mobile” = “4567”>DDD
<option value=“5” “data-mobile” = “5678” selected>EEE

Thanks in advance. It will reduced few io trip


#2

01: You can attach any additional data that you want to in your JSON structure, but that data is only stored in the Select2 widget (or possibly in the HTMLOption objects that Select2 uses to render the <select> element; you wont’ see that data in the rendered <option> elements in the DOM. However, once you have initialized the Select2 widget, you usually don’t need to interact with the underlying <select> element in the DOM. Is there a reason why you need to expose this data in the rendered DOM elements? If it is to expose this data to other frameworks (for example, jQuery, Angular, React, etc.) there are other ways to deal with that.

To set an item as selected, include a field in your JSON item "selected": true (see this documentation).

02: If you want to load your data from an AJAX source only once, just use an AJAX method outside of the Select2 widget (such as jQuery’s AJAX capability, or plain JavaScript’s XMLHttpRequest object or the new fetch() function), and then use that data to initialize the Select2 (exactly like you’re doing with your JSON in 01).


#3

Hi, John30013.
I have the same problem, but when i try to set “selected”: true in JSON data.It fix selected, i cant change to another option. When im view code in Results.prototype.setClasses, why we compare item.element == null

Results.prototype.setClasses = function () {
var self = this;

this.data.current(function (selected) {
  var selectedIds = $.map(selected, function (s) {
    return s.id.toString();
  });

  var $options = self.$results
    .find('.select2-results__option[aria-selected]');

  $options.each(function () {
    var $option = $(this);

    var item = Utils.GetData(this, 'data');

    // id needs to be converted to a string when comparing
    var id = '' + item.id;

    if ((item.element != null && item.element.selected) ||
        (item.element == null && $.inArray(id, selectedIds) > -1)) {
      $option.attr('aria-selected', 'true');
    } else {
      $option.attr('aria-selected', 'false');
    }
  });

});

};


#4

Just to be clear, I didn’t write the Select2 code, but I’ve used Select2 a lot and I’ve made it do a lot of things it wasn’t originally designed to do.

Having said that, I believe the logic you’re asking about, (item.element == null && $.inArray(id, selectedIds) > -1), detects whether the selected item is in the AJAX data but has not been rendered to the underlying HTML <select> element. When you use Select2 with an AJAX data source, Select2 does not create an <option> element in the HTML <select> for each item that is retrieved via AJAX, it only creates an <option> element when the user makes a selection in the widget. Therefore, it is possible that some of the items in the AJAX results data may have selected: true even though the user has not selected those items and thus they are not rendered as <option> elements in the HTML <select>.

I hope that explanation makes sense.

But your real problem seems to be that when you’ve set selected: true in your JSON data, it renders the widget with that item already selected, but then you cannot select any other item. I’m not sure why that’s happening, and it would be helpful if you could provide your code—ideally on CodePen.io or JSFiddle.net, so I can investigate further.