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