Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Select2, how to access ajax data at on(change) function?

I'm using Select2 with ajax. Everything works fine, when the user click on the item they want, I use the on(change) function as specified by the documentation for doing some stuff.

  $("#e6").on("change", function(e) {          
        $('input#Destination').val(e.val); 
          });

});

The return value (e.val) is the data.id value from the ajax call, but my data object has "name", "id" and "type".

I can add code to dataFormatSelection() but this doesn't sound logic and is confusing.

     function dataFormatSelection(data) {
    console.log(data.name + "|" data.id + "|" + data.type);
     return data.name;
 }

How can I access the whole data object (instead of just data.id) at the on("change".. event?

like image 743
Alex Angelico Avatar asked Feb 27 '13 00:02

Alex Angelico


2 Answers

$("#e6").on('change', function(e) {
    // Access to full data
    console.log($(this).select2('data'));
});
like image 188
WebPal Avatar answered Oct 15 '22 18:10

WebPal


According to Select2 docs change event should have 3 properties: The event object contains the following custom properties:

  • val: the current selection (taking into account the result of the change) - id or array of ids
  • added: the added element, if any - the full element object, not just the id
  • removed: the removed element, if any - the full element object, not just the id

There is even example:

$("#e11").select2({
    placeholder: "Select value ...",
    allowClear: true,
    data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});

$("#e11_2").select2({
    placeholder: "Select value ...",
    multiple: true,
    data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});

$("#e11").on("change", function(e) { 
    console.log(JSON.stringify({val:e.val, added:e.added, removed:e.removed})); 
}).on("open", function() { 
    console.log("open"); 
});

$("#e11_2").on("change", function(e) { 
    console.log(JSON.stringify({val:e.val, added:e.added, removed:e.removed})); 
}).on("open", function() { 
    console.log("open"); 
});

But I noticed that added and removed properties are only present when multiple: true is on. I don't know if this is by design or is it bug. I am going to report it anyway, because having the selected element available on change is definitely something needed.

like image 32
Primoz Rome Avatar answered Oct 15 '22 17:10

Primoz Rome