2011-01-09 72 views
3

一直在尋找Jquery UI的自動完成(v1.8.5),並意識到有一個嚴重缺乏發送額外參數和拍攝額外數據來自動填充其他字段的文檔。我的工作,但認真,似乎是這樣一個黑客......任何想法如何改善這一點?Jquery UI自動完成額外參數和自動填充 - 一個沮喪的解決方案

 <script type="text/javascript"> 

     var optofirst = { 

      width: 375, 

      // doing "$(this)" here fails 

      source: function(request, response) { 

      // grab the calling element 
      // "$(this)" here works but ya gotta dig to get to the ID 

      var cat = $(this); 
      var callid = cat[0].element.context.id; //digging away 

      $.ajax({ 

       // doing "$(this)" here fails 

       url: "automagic.php", 
       dataType: "json", 
       data: { 
       term : request.term, 

       //send its ID to the php script 
       grab : callid, 
      }, 

      success: function(data) { 
       response($.map(data, function(item) { 
       return { 

       // start assigning item handles to the response 

       label: item.first, 
       value: item.first, 
       last: item.last, 
       } 
       })); 
      } 
      }); 
     }, 
      select: function(event, ui) { 
       console.log(ui.item ? 
       "Selected: " + ui.item.last : 
       "Nothing selected, input was " + this.value); 

       // make #lname have the value last name 
       // the "item" in this case appears to get its info from the handles assign in "success:" 

       $("#flyover #lname").attr("value",ui.item.last); 
      }, 
     minLength: 2, 
     }; 

     $("#flyover #fname").autocomplete(optofirst); 

     </script> 

回答

1

總的想法對我來說很好看。您的代碼非常接近jQueryUI's custom data and display demo

有可以改進的幾件事情,但:

  1. // doing "$(this)" here fails這兩個選項中的對象並自動完成你的AJAX調用,因爲this在JavaScript不使對象文本的意義;它包含函數調用的上下文(有關this的詳細說明,請參閱this question);
  2. source函數中,this可以工作,因爲現在它有一個函數。 this有一個上下文。
  3. 相反的:

    var callid = cat[0].element.context.id; //digging away 
    

    你可以寫:

    var calid = this.element.attr('id'); 
    

    這是因爲this在這種情況下已經是一個jQuery對象。 $(this)是多餘的。此外,element屬性也是一個jQuery對象,所以你可以使用attr()

其餘的看起來不錯我剛剛訪問id。看看我引用的演示 - 它做了一些類似的事情,你試圖完成。

+0

感謝安德魯爲此在軌3.1!這實際上很有幫助。甚至沒有想過如何將「this」包含在ajax調用的大括號內,我是說在對象字面上不是函數調用。非常感激!你的「this.element.attr('id');」工作得很好!你搖滾! – eSteimann 2011-01-11 20:15:14

2

您可以使用source屬性。設置一個函數,而不是一個url。 您應該只需要編輯url並將customData行替換爲要發送到服務器的多個自定義屬性。 例如:

 $(this).autocomplete({ 
      source: function(request, response) { 
       $.ajax({ 
        url: 'data.php', 
        dataType: "json", 
        data: { 
        term : request.term, 
        customData : $('#something').val() 
        }, 
        success: function(data) { 
        response(data); 
        } 
       }); 
      }, 
      minLength: 3}, { 

     });