0

I use typeahead/bloodhound to autofill an input. My site has more then 20 input fields, all with class typeahead and an id attribute.

My Problem is, I need a request with the %QUERY and a %CID. %QUERY is the search the user typed in one of the input fields and %CID should be the ID from the active input field.

This is my code:

            var search_artikel = new Bloodhound({
            datumTokenizer: function(d) {
                return d.tokens;
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            remote: {
                url: "modules/pc_config/ajax.php?load=search_articles&cat_id=%CID&search=%QUERY",
                replace: function(url, query) {
                    //var cat = this.id;
                    //return url + "&cat_id=" + cat + "&search=" + query;
                    return url.replace('%QUERY', query).replace('%CID', $(this).attr('id'));
                }
            }
            //remote: 'modules/pc_config/ajax.php?load=search_articles&search=%QUERY'

        });

        search_artikel.initialize(this.id);

        $('.typeahead').typeahead({
            hint: true,
            highlight: true,
            minLength: 4
        },
        {
            name: 'phonenumber',
            displayKey: 'number',
            source: search_artikel.ttAdapter(),
            templates: {
                suggestion: Handlebars.compile([
                    '<p class="bold">{{number}}</p>',
                    '<p class="small"><i>{{name}} {{surname}}</i></p>',
                    '<p class="small"><i>{{address}}</i></p>',
                ].join(''))
            }
        });

Everything works fine except the %CID is always "undefined". How can I replace the %CID with the active/focus id from the input field?

bigtunacan
  • 4,873
  • 8
  • 40
  • 73

1 Answers1

3

I know this may be a little old, but I came across it in a search, so I thought I'd provide an answer. In short, your idea to use the following is correct:

            replace: function(url, query) {
                //var cat = this.id;
                //return url + "&cat_id=" + cat + "&search=" + query;
                return url.replace('%QUERY', query).replace('%CID', $(this).attr('id'));
            }

However, your scope is off in that $(this) will not give you the jQuery element you believe you're trying to get. Since the beginning of your code is cutoff, I can't provide you a specific answer to your code, but if you updated:

$(this).attr('id')

To be something like:

$("#some-selecter").attr('id')

It would work as intended.

conrad10781
  • 2,223
  • 19
  • 17