Victor Leal
Victor Leal

Reputation: 1065

Adding "data-" attributes with select2

I've seen a lot examples of Select2 option tags set with "data-" attributes and I would like to do it.

I'm using ajax to get the data. I get the ID and the TEXT needed to build the select.

But how can I add more attributes to it?

I just didn't find the way to add them.

$(element).select2({
    placeholder: 'Select one...',
    width: '100%',
    minimumInputLength: 2,
    ajax: {
        url: '/my/url',
        dataType: 'json',
        data: function(params) {
            return {
                q: params.term,
                page: params.page
            };
         },
         processResults: function(data, page) {
             console.log(data);
             return {
                 results: data
             };
         },
         cache: true
     }
 });

Upvotes: 23

Views: 45450

Answers (5)

croppio.com
croppio.com

Reputation: 1883

Another option is to set the title attribute of the <option> tag. This way the select2('data') function will return it.

This is a good approach when the select is build on the server side.

Upvotes: 0

Ahmet Firat Keler
Ahmet Firat Keler

Reputation: 4040

select2 has an option called templateSelection

In the example below, I set another data field called 'staff_constant' on each option of my select2 element. I use ajax option because I get all the data from an endpoint.

Data structure:

{
  "id": 16471,
  "text": "Mmxmxm",
  "staff_constant": 6948
}

select2 instantiation:

$( ".select2" ).select2({
  // other option fields...

  // loading options from an endpoint
  ajax: {
    url: "{{route('customers.search')}}",
    type: "post",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        _token: CSRF_TOKEN,
        search: params.term // search term
      };
    },
    processResults: function (response) {
      return {
        results: response
      };
    },
    cache: true
  },

  // I set `staff_constant` field here
  templateSelection: function (data, container) {
    $(data.element).attr('data-staff_constant', data.staff_constant);
    return data.text;
  },

  // other option fields...
});

Then I can access the selected option's staff_constant field like that

HTML

<select id="customer-field" onchange="selectStaff(this)" class="custom-select select2" name="customer" required>
</select>

JS

function selectStaff(e) {
  var staff_constant = $(e).find(':selected').data('staff_constant');
}

Further reading https://select2.org/programmatic-control/retrieving-selections

Upvotes: 2

Jeffrey - Humanized
Jeffrey - Humanized

Reputation: 801

This solution applies to Select2 versions 4.0 or higher.

Assuming the attributes your talking about are loaded in the array you are returning in processResults. For example, if you are selecting a record like ('id':1,'text':'some-text','custom_attribute':'hello world')

Then on a change event you can do:

data=$("#selector").select2('data')[0];
console.log(data.custom_attribute);//displays hello world

Hope it helps..

Upvotes: 52

przbadu
przbadu

Reputation: 6049

If your JSON response for ajax call looks like this:

[
  {
    "id": 1,
    "text": "option 1",
    "attr1": "custom attribute 1",
    "attr2": "custom attribute 2"
  },
  {
    "id": 2,
    "text": "option 2",
    "attr1": "custom attribute 3",
    "attr2": "custom attribute 4"
  }
]

Then, select2 seems to add them as data attributes for option automatically,

And this is how you can access them, example in change event:

$(element).on('change', function(e) {
  console.log($(this).select2('data')[0]);
})

In above example, you can now access your json response as select2('data') attribute. example: $(this).select2('data')[0].attr1 will return custom attribute 1

This way I was able to get data required data-attribute for selected option.

Upvotes: 1

Anand Singh
Anand Singh

Reputation: 2363

I am not sure what exactly you are asking but if you want to add data attribute you can do like this..

In Jquery:

$(element).attr('data-info', '222');

In javascript:

document.getElementById('elementId').setAttribute('data',"value: 'someValue'");

Upvotes: 1

Related Questions