Select2 getting invalid results from the last selected selection field

I am currently having a problem where my select2 plugin sometimes shows results from the last select box selected. Also, I also get g.results to be null when I click on the select box first or if I type too fast. My code is as follows.

window.currentField = ""; //current product field data window.currentCategory = ""; //current product category data //lets get some data from the hidden input for providing suggestions via ajax $(".suggestive-entry").live('click',function() { //alert("click called"); //alert("test"); window.currentField = $(this).siblings('input:hidden').attr('data-field'); //get the field attribute // alert(window.currentField); window.currentCategory = $(this).siblings('input:hidden').attr('data-category'); //get the category attribute }); //formats select2 returned option function format(item) { return item.term; }; //used for suggestive search fields $(".suggestive-entry").select2({ createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.term.localeCompare(term)===0; }).length===0) { return {id:term, term:term};} }, initSelection : function (element, callback) { var data = {id: element.val(), term: element.val()}; callback(data); }, multiple: false, ajax: { url: "includes/ajax/map-fields.php", dataType: 'json', data: function (term, page) { //alert("suggestive called"); return { q: term, field: window.currentField, ptype: window.currentCategory }; }, results: function (data, page) { return { results: data }; } }, formatSelection: format, formatResult: format }); 

Any help would be greatly appreciated.

+4
source share
1 answer

try to give id to your hidden field, do something like this

  data: function (term, page) { //alert("suggestive called"); var data_field = $('#someId').attr('data-field'); var data_category = $('#someId').attr('data-category'); return { q: term, field: data_field, ptype: data_category }; } 
+1
source

Source: https://habr.com/ru/post/1480481/


All Articles