4

I am using auto complete for multiple input text elements, I want to get data from different function depending upon the element which triggered the event, as I am passing the web service link in data attribute of text element. I dont want to write different auto complete 3 times in page.

HTML:-

<input class="autocomplete" name="firstname" link='getfirstname'/>
<input class="autocomplete" name="middlename" link='getmiddlename'/>
<input class="autocomplete" name="lastname"
link='getlastname'/>

Jquery :-

$('.autocomplete').autocomplete({
    source: function (request, response) {
        jQuery.get($(this).data('link'), {
                typedValue: request.term
            }, function (data) {
                response(data);
            }, 'json');
        },
        minLength: 1
})

Demo

I refereed How to get the input element triggering the jQuery autocomplete widget? but was of no help.

Community
  • 1
  • 1
Daxesh Vora
  • 579
  • 5
  • 16

1 Answers1

3

Instead of $(this).data you need to use $(this.element).data JSFiddle

$('.autocomplete').autocomplete({
    source:function(request, callback){
        console.log($(this.element).data("link"));
        jQuery.get($(this.element).data('link'), {
                typedValue: request.term
            }, function (data) {
                response(data);
            }, 'json');
    },
    select: function(event, ui) {
        console.log(event.target.name);
        console.log($(this).prop('name'));
        console.log($(event.target).data("link"));
    }
})
Martin
  • 2,411
  • 11
  • 28
  • 30