4
我目前有一个问题,现在我的select2插件有时显示最后选择的选择框的结果。当我第一次点击选择框或者输入太快时,我也会得到g.results有时为空。我的代码如下。Select2从上次选择的选择框中检索无效结果
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
});
任何帮助将不胜感激。
有没有人有什么建议?也许我的问题不够清楚? – 2013-05-13 23:51:20
你能提供一个jsFiddle吗? – 2013-05-15 15:15:48
感谢您的回复,也许更好的问题是如何访问来自select2的隐藏输入的数据属性。我试图在我的ajax调用中传递数据元素,就像你在我的数据调用中看到的那样(field&ptype)。我认为我的问题是,我的点击事件是在不同的时间点击,然后select2的onchange事件,因此它从最后一个选择框中获取field&ptype。看着我的XHR请求让我想到这一点。 – 2013-05-16 20:34:44