2017-04-13 49 views
1

我遇到了JQuery的問題。用戶從自動填充下拉菜單<input class="itemCode">中選擇一項後,我需要填寫<input class="itemDescription">。 JQuery工作正常,只有當用戶選擇item時,第1行和第2行的兩個輸入都填充了相同的項目描述。我認爲這個問題是itemDescription輸入具有相同的類別。但是,我不知道如何解決它。任何幫助將不勝感激!JQuery自動完成填充選擇的所有行

<table class="table"> 
    <thead> 
     <tr> 
     <td >Item Code</td>    
     <td >Description</td> 
    </tr> 
    </thead> 
    <tbody> 
    <tr> 
     <td class=""><input class="itemCode"></td>    
     <td class=""><input class="itemDescription"></td> 
    </tr> 

    <tr> 
     <td class=""><input class="itemCode"></td>    
     <td class=""><input class="itemDescription"></td> 
    </tr> 
    </tbody> 
</table> 


<script> 
    $(function() { 
    $(".itemCode").autocomplete({ 
     source: function(request, response) { 
     $.ajax({ 
      url: "item-search.php", 
      dataType: "json", 
      data: { 
      term: request.term 
      }, 
      success: function(data) { 
      response(data); 
      } 
     }); 
     }, 
     minLength: 1, 
     select: function(event, ui) { 
      $(".itemDescription").val(ui.item.label); 
     } 
    }); 
    }); 
    </script> 

回答

1

使用給定的上下文引用正確的輸入。請嘗試以下操作:

$(this).parent().next().children(".itemDescription").val(ui.item.label); 

如果你想讓它爲您可能添加任何領域的工作,使用以下命令:

$(this).parent().siblings().children(".itemDescription").val(ui.item.label); 
+0

工程就像一個魅力!謝謝! – Luke

+0

如果我爲例如'itemPrice'添加一個附加字段,語法應該是什麼樣子?如果我試試這個:'(this).parent()。next()。children(「。itemDescription」)。val(ui.item.itemDescription); \t $(this).parent()。next()。children(「。itemCost」).val(ui.item.itemCost);' 然後新的字段itemPrice沒有被填充。謝謝! – Luke

+0

您可以添加額外的'.next()'或使用我編輯的解決方案。我會建議我編輯的解決方案,因爲它更一般。 –

0

試着將結果發送給它找到的那個類的第一個實例。

$(".itemDescription").val(ui.item.label); 

將設置該類的所有元素作爲該值。如果您只想設置第一個,請使用類似

$(".itemDescription").first().val(ui.item.label); 
+0

我只是把它改爲'$(「.itemDescription」)。一().val(ui.item.label);'但現在只有第一個被填充。 – Luke

+0

我應該用「this」來代替嗎? – Luke

+0

你需要嘗試在jQuery中找到一種方式來獲取'當前輸入字段'的索引(位置),然後使用該索引來定位特定的描述字段 – tamak

相關問題