Home > Software engineering >  using selectors in jquery ui / autocomplete / source
using selectors in jquery ui / autocomplete / source

Time:09-18

Say I have the following HTML:

<div class="name">
First: <input type="text" name="firstName" class="firstName">
Last: <input type="text" name="lastName" class="lastName">
</div>

Here's the JS that corresponds to that HTML:

$('.lastName').last().autocomplete({
    source: function(request, response) {
    var firstName = $('.firstName', $(this).closest('.name'));
    var lastName = request.term;
    console.log(firstName   ' '   lastName);
  }
});

I'd like to have autocomplete pull the closest .firstName to the .lastName field that the source method is linked to but it's not working.

Superficially it seems like if that's not gonna work that I could attach some sort of unique ID to .lastName but if the only thing I can access is request then it's not like I can simply add a data-whatever attribute to the <input> element.

Any ideas?

Here's my JS Fiddle: https://jsfiddle.net/f86nLrq9/

CodePudding user response:

Consider the following: https://jsfiddle.net/Twisty/39mrzowc/39/

JavaScript

$(function() {
  $('.lastName:last').autocomplete({
    source: function(request, response) {
      var fName = $(this.element).prev().val();
      console.log(fName, request.term);
      response([]);
    },
  });
});

If you examine this, you will see it is a reference to the Autcomplete Instance (a data Object). Most of the Widgets have a reference to the Element, see: https://api.jqueryui.com/jQuery.widget/

That means that this, was not a reference to the element input.lastName; hence, the code you were using was not working. Your same code with this minor change will work too: https://jsfiddle.net/Twisty/yucabv8m/1/

JavaScript

$('.lastName').last().autocomplete({
    source: function(request, response) {
    var firstName = $('.firstName', $(this.element).closest('.name')).val();
    var lastName = request.term;
    console.log(firstName   ' '   lastName);
  }
});
  • Related