shaharsol
shaharsol

Reputation: 1010

Two bootstrap typeaheads on same page with two different source functions

I'd like two different text inputs to have typeahead, each with a different source function. For the sake of example, one gets first_names and the other last_names.

Here's how it looks and it's not working:

$('#first_name').typeahead({
    source: function (query, process) {
        $.get('/users/typeahead-first-name', { term: query }, function (data) {
            return process(JSON.parse(data));
        });
    }
});

$('#last_name').typeahead({
    source: function (query, process) {
        $.get('/users/typeahead-last-name', { term: query }, function (data) {
            return process(JSON.parse(data));
        });
    }
});

The first typeahead works fine. However, the 2nd one, when I start typing and the options start to appear, then I click an option, the dropdown just closes and no value is inserted into the input field.

Anybody's got any idea how to get it to work?

Upvotes: 5

Views: 2660

Answers (1)

keredson
keredson

Reputation: 3088

This may be a little late to help you, but I just had the same problem in my own app. The solution was to add "name" attributes, like this:

$('#first_name').typeahead({
    name: 'first_name',
    source: function (query, process) {
        $.get('/users/typeahead-first-name', { term: query }, function (data) {
            return process(JSON.parse(data));
        });
    }
});

$('#last_name').typeahead({
    name: 'last_name',
    source: function (query, process) {
        $.get('/users/typeahead-last-name', { term: query }, function (data) {
            return process(JSON.parse(data));
        });
    }
});

It didn't matter what I called them in my code, as long as they were different. It makes some sense too, since typeahead keeps a cache of responses. (Although I would have thought they would have just tied the cache to the instance you're binding it to, but...)

Upvotes: 4

Related Questions