Domanda

I'm using jquery.autocomplete for searching items by code and autocomplete the code and also update previous form input field called name:

<tr>
<td><input type="text" name="Name[]" class="nameautoc" value="badname1" /></td>
<td><input type="text" name="Code[]" class="codeautoc" value="1234" /></td>
</tr>
<tr>
<td><input type="text" name="Name[]" class="nameautoc" value="ok_name" /></td>
<td><input type="text" name="Code[]" class="codeautoc" value="12345" /></td>
</tr>
<tr>
<td><input type="text" name="Name[]" class="nameautoc" value="badname2" /></td>
<td><input type="text" name="Code[]" class="codeautoc" value="34567" /></td>
</tr>

The autocomplet by the code itself works ok, for each Code input field. When added the JS code to update the matching Name field, it update the whole form Name fields instead of the previous/or the current one I'm working on.

How can I implement that only the current input Name field is autocompleted by the code I choose, or should I use JS code refering to the table I'm using?

The JS code:

    $(document).ready(function($) { 
        $(".codeautoc").autocomplete({
            source:"codenName.php",
            minLength:2,
            select:function(event,ui){
                var item=ui.item;
                if(item){
                    $(".nameautoc").val(item.name);
                }
            }
    });

The relevant PHP code:

    while($row = mysql_fetch_array($fetch,MYSQL_ASSOC)) {
        $return_row['label'] = $row['code'];
        $return_row['value'] = $row['code'];
        $return_row['name'] = $row['name'];
        array_push($return_arr, $return_row);
    }

Hope I provided the needed information.

Thanks!

È stato utile?

Soluzione

Your select callback should look something like this:

  select:function(event,ui){
      var item=ui.item;
      if(item){
         $(".nameautoc", $(this).parents('tr')).val(item.name);
      }
  }

By adding $(this).parents('tr') as context in the jquery selector (Refer to JQuery docs for more details), you're making sure that only the matching child elements of the parent tr element are updated, instead of all elements with class nameautoc in the document.

Optionally, you can also use $(this).parent().parent() to traverse upto the tr, instead of using $(this).parents('tr'). Here's the working fiddle.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top