JQuery Autocomplete在select处填充所有行

时间:2017-04-13 23:53:33

标签: jquery autocomplete

我遇到了JQuery的问题。用户从自动填充下拉菜单<input class="itemDescription">中选择一个项目后,我需要填充<input class="itemCode">。 JQuery工作正常,只有当用户选择item时,第1行和第2行的两个输入都填充了相同的项目描述。我认为问题是两个itemDescription输入具有相同的类。但是,我不知道如何解决它。任何帮助将不胜感激!

<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> 

2 个答案:

答案 0 :(得分:1)

使用给定的上下文引用正确的输入。请尝试以下方法:

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

如果您希望它适用于您可以添加的任何字段,请使用以下命令:

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

答案 1 :(得分:0)

尝试将结果解析为它找到的该类的第一个实例。

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

将该类的所有元素设置为该值。如果您只想设置第一个,请使用类似

的内容
$( ".itemDescription" ).first().val( ui.item.label );