2013-04-22 59 views
0

我在頁面上有幾個輸入框,所有的都帶有自動完成類,在它們的每一個下面我有一個div,我希望自動完成結果被附加到。然而,如果我只是說追加到一個類的div,那麼它只是做第一個div而不是最接近的那個。我試圖把一些javascript放在一起來解決這個問題,但是我碰到了一堵磚牆,並且一直在收到相同的錯誤。任何可以提供的幫助表示讚賞。使用jQuery自動完成追加到類的最近的div

這裏是我的javascript:

<script type="text/javascript"> 
$(document).ready(function() { 
    var div_id; 
    $("input.autocomplete").autocomplete({ 
     set: div_id = $(".autocomplete").keyup(function() { 
      $('.autocomplete').closest('div').find('.container').attr('id'); 
     }), 
     appendTo: div_id, 
     source: function (request, response) { 
      $.ajax({ 
       url: '/Home/GetUsers', 
       type: "POST", 
       dataType: "json", 
       data: { query: request.term }, 
       success: function (data) { 
        response($.map(data, function (item) { 
         return { label: item, value: item }; 
        })); 
       } 
      }); 
     } 
    }); 
})  
</script> 

這裏是視圖的樣子:

Employee Name (Team Leader): <input type ="text" name="empName1" class="autocomplete"/> 
    <div class ="container" id = "container0"></div> 
    <br/> 
    <br/> 
    Employee Name (Event Process Owner): <input type ="text" name="empName2" class="autocomplete"/> 
    <div class ="container" id = "container1"></div> 
    <br/> 
    <br/> 
    Employee Name (Sponsor): <input type ="text" name="sponsor" class="autocomplete"/> 
    <div class ="container" id = "container2"></div> 
    <br/> 
    <br/> 
    Employee Name: <input type ="text" name="empName3" class="autocomplete"/> 
    <div class ="container" id = "container3"></div> 
    <br/> 
    Employee Name: <input type ="text" name="empName4" class="autocomplete"/> 
    <div class ="container" id = "container4"></div> 
    <br/> 

而且我得到當我嘗試啓動該項目的錯誤是「Microsoft JScript運行時錯誤:意外的調用方法或屬性訪問。「當我得到這個錯誤它強調這在我的jquery.min.js(1.8.3):

this.appendChild(e) 

回答

0

改變這一行

$('.autocomplete').closest('div').find('.container').attr('id'); 

$('.autocomplete').next("div").attr("id")); 

應該不錯。

+0

當我嘗試,我得到錯誤「Microsoft JScript運行時錯誤:無法獲取屬性的值'元素':對象爲空或未定義」在「if(this.menu.element.is(」:visible「))」jquery-ui-1.8 .20.js – 2013-04-22 14:02:21

0

試試這個:

HTML

添加data container idinput box

Employee Name (Sponsor): 
<input type ="text" name="sponsor" data-container_id="container2" class="autocomplete" /> 
<div class ="container" id = "container2"></div> 

現在腳本

$("input.autocomplete").autocomplete({ 
    appendTo: $('#'+$(this).data('container_id')),//it will give you container-id 
    .... 
    .... 
+0

感謝您的回覆。當我嘗試獲取錯誤「Microsoft JScript運行時錯誤:意外調用方法或屬性訪問權限」。在jquery.min.js – 2013-04-22 13:56:22

+0

的同一個地方我剛剛嘗試了你的第三個建議,我得到錯誤「Microsoft JScript運行時錯誤:無法獲取屬性的值'元素':對象爲null或未定義」at「var ul = this.menu.element \t \t \t .empty() \t \t \t .zIndex(this.element.zIndex()+ 1);」在jquery-ui-1.8.20.js – 2013-04-22 14:06:57

+0

@Danger_Fox嘗試上面的代碼我改變了使用它的方式。 – 2013-04-23 05:55:15