Javascript 选择2从上次选择的选择框中检索无效结果
我现在遇到了一个问题,我的select2插件有时会显示上次选中的选择框的结果。此外,当我第一次单击选择框或如果我键入太快时,我也会得到g.results。我的代码如下Javascript 选择2从上次选择的选择框中检索无效结果,javascript,jquery,jquery-select2,Javascript,Jquery,Jquery Select2,我现在遇到了一个问题,我的select2插件有时会显示上次选中的选择框的结果。此外,当我第一次单击选择框或如果我键入太快时,我也会得到g.results。我的代码如下 window.currentField = ""; //current product field data window.currentCategory = ""; //current product category data //lets get some data fr
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
});
任何帮助都将不胜感激 尝试为隐藏字段指定id,执行以下操作
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
};
}
有人有什么建议吗?也许我的问题不够清楚?你能提供一个JSFIDLE吗?谢谢你的回答,也许更好的问题是如何从select2访问隐藏输入的数据属性。我试图在ajax调用中传递数据元素,正如您在我的数据调用(field&ptype)中看到的那样。我认为我的问题是,我的点击事件在不同的时间触发,然后选择2的onchange事件,因此它从最后一个选择框中获取field&ptype。看着我的XHR请求让我想到了这一点。你能解释一下隐藏字段的用途和位置吗?select2插件将隐藏字段呈现为修改后的文本框。我已将数据属性附加到此元素,并希望将这些元素中包含的信息传递给当前正在使用的select2元素。我试图通过使用上面显示的方法来实现这一点,但有时它会提供来自先前选择的select2元素的数据;var data_category=$(this.attr('data-category');因为我的select2处理所有的选择框。谢谢你的帮助!我以前也试过类似的方法,但肯定有点不对劲,所以我放弃了这个想法。