Jquery Select2, how to access ajax data when function (change) is enabled?

I am using Select2 with ajax. Everything works fine, when the user clicks on the item that they need, I use the on (change) function, as indicated in the documentation to perform some actions.

$("#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 " .

I can add code to dataFormatSelection (), but that doesn't sound logical and confusing.

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

How can I access the entire data strong> object (and not just data.id ) when ("change" .. event is turned on?

+7
source share
3 answers
 $("#e6").on('change', function(e) { // Access to full data console.log($(this).select2('data')); }); 
+18
source

According to Select2 docs, an event must have 3 properties: the event object contains the following custom properties:

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

There is even an 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 the added and removed properties are only present when multiple: true enabled. I do not know if this is by design or this is a mistake. I am going to report this anyway, because having the selected item available for change is definitely necessary.

+2
source

I have doubts ... How can I accept the values ​​displayed in the console log and use them?

is it correct if i take these values ​​and put each in var? Because if I use console.log (var) for any var created, this value is displayed, but if a makes a warning (var), the warning is never displayed.

I need to accept the value of the parameter selected for calling with the AJAX function of PHP.

 $("#e11").on('change', function(e) { //I create a var data and works it like an Array var data = $(this).select2('data'); //Then I take the values like if I work with an array var value = data.id; var text = data.text; //If I use console.log(var) the values are displayed but not with an alert } 

Thanks!!!

0
source

All Articles