Referencing the text input from within jQuery autocomplete
Asked Answered
S

1

9

Given the following code, how can I reference the input that has autocomplete bound to it from within the success() function in the $.ajax call? Neither $(this) or $e work.

$('.parent-input').autocomplete({
  source: function(request, response) {
    $.ajax({
      url: "/chunky/bacon",
      dataType: 'json',
      data: {
        product_id: $('#product-id').val(),
        term: request.term
      },
      success: function(data){
        var resultCount = data.length;
        // I NEED TO REFERENCE .parent-input HERE
        response( data );
      }
    });
  },
  minLength: 2,
  select: function(event, ui){
    addAssociatedProduct(ui.item.id, ui.item.value);
    $(this).val('');
    return false;
  }
});
Scratchboard answered 22/6, 2011 at 17:26 Comment(1)
Are there multiple elements of class parent-input? If not, why not just give it an id of parent-input instead, and reference it using the selector function?Luxembourg
W
8

Save a reference to this.element (this.element is a jQuery object so there's actually no need to wrap it in another jQuery call):

$('.parent-input').autocomplete({
  source: function(request, response) {
    var element = this.element; // <-- this.element is the input the widget is bound to.
    $.ajax({
      url: "/chunky/bacon",
      dataType: 'json',
      data: {
        product_id: $('#product-id').val(),
        term: request.term
      },
      success: function(data){
        var resultCount = data.length;
        // element still refers to the input the widget is bound on.
        // for example:

        element.addClass("blue");

        response( data );
      }
    });
  },
  minLength: 2,
  select: function(event, ui){
    addAssociatedProduct(ui.item.id, ui.item.value);
    $(this).val('');
    return false;
  }
});
Weber answered 22/6, 2011 at 17:30 Comment(5)
If you're going to use var element=this;, you'll probably have to add the context: element parameter to the ajax callLuxembourg
@hughes: Actually I don't think you have to, but it would enable you to use $(this) inside of the success function of the AJAX call.Weber
Oh yeah, you're right. In that case, does element become a global variable? Or is the success function within the scope of of element's declaration? Or does all that not even matter in JS?Luxembourg
@hughes: No, element is scoped to the source function.Weber
Excellent! And I just found there is no need to declare the "element" variable, in the success handler can refer to $(this)[0].elementGorrian

© 2022 - 2024 — McMap. All rights reserved.