Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set data attributes with ajax and select2

I'm trying setup data attributes into select2 options but without success, at this moment i have the following JS code

_properties.$localElement.select2({
    ajax: {
        url: "url",
        type: "POST",
        dataType: 'json',
        delay: 250,
        data: function (params) {
        return {
            name: params.term, // search term
            type: 1
        };
        },
        processResults: function (data) {

            return {
            results: $.map(data, function (item) {
                return {
                    text: item.name,
                    source: item.source,
                    id: item.id
                }
                })
            };
        },
        cache: true
    },
    //define min input length
    minimumInputLength: 3,

});

And i want setup a data-source for the selected option value.

like image 454
Rubem Mota Avatar asked Sep 15 '16 15:09

Rubem Mota


2 Answers

You can actually use the exact syntax, that you already used. The "source-attribute" just needs to be accessed via data().data.source of the specific select2-option.

So keep your processResults function like you did:

processResults: function (data) {
   return {
      results: $.map(data, function (item) {
         return {
            text: item.name,
            source: item.source,
            id: item.id
         }
      })
   };
},

and if you want to retrieve the source of the selected option, you can do it like this:

var selectedSelect2OptionSource = $("#idOfTheSelect2 :selected").data().data.source;

In fact you can set any variable you want in your processResults function and then select it via data().data.variableName!

like image 156
Philipp Poropat Avatar answered Sep 16 '22 13:09

Philipp Poropat


I solved this problem.

$('select').on('select2:select', function (e) {
    var data = e.params.data;
    $("select option[value=" + data.id + "]").data('source', data.source);
    $("select").trigger('change');
});
like image 37
Mehmet Izmirlioglu Avatar answered Sep 19 '22 13:09

Mehmet Izmirlioglu