2

Is there any way to get input element on Autocomplete source function? $(this) not referring to input of autocomplete instance.

jsFiddle sample here.

<input type="text" data-code="foo" placeholder="type something ..." class="suggest" />
<input type="text" data-code="foo2" placeholder="type something ..." class="suggest" />

JavaScript

$(".suggest").autocomplete({
            delay: 100,
            source: function (request, response) {

                // get foo here,: $(this).data("code"); not working

                // Suggest URL
                var suggestURL = "http://suggestqueries.google.com/complete/search?client=chrome&q=%QUERY";
                suggestURL = suggestURL.replace('%QUERY', request.term);

                // JSONP Request
                $.ajax({
                    method: 'GET',
                    dataType: 'jsonp',
                    jsonpCallback: 'jsonCallback',
                    url: suggestURL
                })
                .success(function(data){
                    response(data[1]);
                });
            }
        });
4
  • You mean you wanna access the $("#suggest") within the Autocomplete source function? Commented Jan 5, 2017 at 16:17
  • Yes, but not with $("#suggest") selector. I need relative one Commented Jan 5, 2017 at 16:18
  • relative one? Sorry I don't quite get it. Can you elaborate a bit? if you need this itself to do something, you can save it tho. Commented Jan 5, 2017 at 16:28
  • @MichelleTan, I have just edit question. think that i have 2 input, and init autocomplete with class selector. i need input of autocomplete in source function. Commented Jan 6, 2017 at 5:41

1 Answer 1

2

this.element gets the current element on source function.

$(".suggest").autocomplete({
            delay: 100,
            source: function (request, response) {

                this.element.data("code"); 

                // Suggest URL
                var suggestURL = "http://suggestqueries.google.com/complete/search?client=chrome&q=%QUERY";
                suggestURL = suggestURL.replace('%QUERY', request.term);

                // JSONP Request
                $.ajax({
                    method: 'GET',
                    dataType: 'jsonp',
                    jsonpCallback: 'jsonCallback',
                    url: suggestURL
                })
                .success(function(data){
                    response(data[1]);
                });
            }
        });

Working sample here

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.