2013-05-13 50 views
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 
     }); 

任何幫助將不勝感激。

+0

有沒有人有什麼建議?也許我的問題不夠清楚? – 2013-05-13 23:51:20

+1

你能提供一個jsFiddle嗎? – 2013-05-15 15:15:48

+0

感謝您的回覆,也許更好的問題是如何訪問來自select2的隱藏輸入的數據屬性。我試圖在我的ajax調用中傳遞數據元素,就像你在我的數據調用中看到的那樣(field&ptype)。我認爲我的問題是,我的點擊事件是在不同的時間點擊,然後select2的onchange事件,因此它從最後一個選擇框中獲取field&ptype。看着我的XHR請求讓我想到這一點。 – 2013-05-16 20:34:44

回答

1

儘量給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 
      }; 
    } 
+0

在我的情況下,我不得不使用以下內容: var data_field = $(this).attr('data-field'); var data_category = $(this).attr('data-category'); 由於我的select2處理所有選擇框。謝謝你的幫助!我之前嘗試過類似的東西,但它一定有點偏離,所以我放棄了這個想法。 – 2013-05-20 11:47:31