Samuel
Samuel

Reputation: 2156

jQuery autocomplete origin

I'm adding autocomplete on several inputs at the same time, thus writing a single handling function as the source. I'd like to have the id attribute of the origin (the input that triggered the action) available in my handling function. But it seems there's no direct reference to it within autocomplete...

$('#inputForm #supplier, #inputForm #label').autocomplete({
    source: function(request, response) {
        $.post("autocomplete.php", {id: ???, term: request.term}, success);
    }
});

Any clue?

Upvotes: 2

Views: 87

Answers (2)

Jaime Sangcap
Jaime Sangcap

Reputation: 2595

you could use

$(this).attr('id')

I suggest you also use a class for all your autocomplete like for example

.autocomplete

and add data- for your extra data like

data-id, data-url

you can get the value of data-xxx attributes by using

$(this).data('id') and $(this).data('url')
enter code here
$(".autocomplete")
.each(function () {
   $(this).autocomplete({
      source : function(request, response) {
    $.post($(this).data('url'), {origin: $(this.).data('id'), term:               request.term}, success);
}
       });
    });

Upvotes: 0

Samuel
Samuel

Reputation: 2156

Got it! Thanks to Richard ;)

 $(this.element).attr('id')

Complete code, in case anyone would be interested:

$('input').autocomplete({
    source: function(request, response) {
        $.post("autocomplete.php", {origin: $(this.element).attr('id'), term: request.term}, success);
    }
});

Upvotes: 2

Related Questions