auto complete jQuery with 2 input

Asked

Viewed 87 times

0

I have the following autocomplete that works in the first input, when completing it fills in the 2nd input.

The problem is that if I delete the tag <p> it doesn’t work. Someone can tell me why?

Follows the code:

$().ready(function() {

  $("#singleBirdRemote").autocomplete("search.php", {
    width: 260,
    selectFirst: false
  });

  $("#singleBirdRemote").result(function(event, data) {
    if (data)
      $(this).parent().next().find("#xx").val(data[0]);
  });

});
<p>
  <input type="text" id="singleBirdRemote">
</p>
<p>
  <input name="asdad" id="xx">
</p>

1 answer

2


I believe this occurs because you retrieve the reference of the second input in a relative way by traversing the DOM tree.

I mean, you’re based on #singleBirdRemote, search for the father p, navigate to the next element and search for input xx. When remove p you break that hierarchy.

 $(this).parent().next().find("#xx").val(data[0]);

You can simply replace the

 $("#xx").val(data[0]);

I believe that alone will help.

Be careful when browsing relative mode, any changes in the code may cause you problems. The ideal is to have precise references, by id, name or class, depending on the need.

  • Good in its form did not work, I found a solution like: $(this). Parent(). find("input[@name=value]"). val(data[3]); what you think?

  • How did you apply the solution? Apparently there were changes in the code, since there is a name in the input and now you index date by 3, not by zero, IE, could apply $("#xx"). val(date[3]);

  • The problem with the solution you used is that you keep using the reference by Parent! This should be avoided when possible! Otherwise your code becomes too dependent on the html hierarchy!

  • thus: https://jsfiddle.net/6gt2z1z8/

  • 1

    Just try $("input[name=b]"). val(data[3]); Have everything to work without relying on the hierarchy!

  • perfect, works 100%

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.