1

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/

4
  • Really not clear how you expect this to work. Typically you have an array of choices to select from. That array would be passed to response(array) in the source callback. What would you use the first name for while trying to select last name? Commented May 7, 2021 at 20:44
  • 1
    FYI to get the value from the adjacent firstname would be $(this).siblings('.firstname').val() Commented May 7, 2021 at 20:47
  • The this is ambiguous. You must use a more specific selector. Commented May 7, 2021 at 20:48
  • Looking into this further, use $(this.element) for proper reference. this is in relationship to the Instance and not the Element. Commented May 7, 2021 at 22:07

1 Answer 1

2

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);
  }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.