Typeahead 3 and Bootstrap - Autocomplete Name & ID

1.1k views Asked by At

I'm only a basic level programmer - writing in PHP and jQuery.

I'm trying to have an autocomplete field in my site that has a text box, and when people start typing, it fetches results from a PHP page of users and ID numbers associated.

I'm combining this with tagsinput - I basically want it to be like Gmail - type someone's name, and have them show up as tags. I need to be able to access the data (particularly the ID - because after selecting names, I'll be writing code to email users based on those IDs).

I can't understand exactly what I need to do though - I've been confused with the different Typeahead plugins - because my site uses Bootstrap 3.

As I understand it - I have to use the bootstrap3-typeahead.min.js file to use. This is included in my page.

From what I can see, most of the work is done - I am having the correct results returned from my ajax call, but the options are not displaying onscreen as I need them to - and I am getting a "TypeError: g is undefined" error in Firebug.

Here is where I am up to so far (I can post anything else that is required):

$('#user_name').tagsinput({
  typeahead: {
    source: function(query) {
      var fetched = $.get('group.php?pa=ajax_get_users&term='+query);
      console.log(fetched);
    }
  }
})

The page referenced above returns a json encoded array of names and IDs, and seems to work. Using firebug, I can see that (for instance) - when I type 'to' into the field, it makes the call and the following is returned:

[{"label":"Toby Behan","id":"2"},{"label":"Toby Behan","id":"3126"},{"label":"Tommy Streisand","id":"3144"}]

The console.log() function shows a valid object returned in Firebug.

What do I need to do to get this properly showing in terms of dropdown and selections?

Thanks for any help.

1

There are 1 answers

0
Bass Jobsen On

I can't understand exactly what I need to do though - I've been confused with the different Typeahead plugins - because my site uses Bootstrap 3.

I think you will have to choose between Bootstrap 3 Typeahead and typeahead.js. Both plugins should work, but you should use only one of them.

Your major issues seems that your group.php returns a array of objects whilst tags-input requires a array of values. You can use jQuery.map() to covert the values.

So when using Bootstrap 3 Typeahead:

$('input').tagsinput({
  typeahead: {                  
    source: function(query) {
      return $.map($.get('group.php?pa=ajax_get_users&term='+query)function(values){return values.label;});
    }
  }
});

Also see https://github.com/bassjobsen/Bootstrap-3-Typeahead#bootstrap-tags-input and https://github.com/bassjobsen/Bootstrap-3-Typeahead/issues/33#issuecomment-38047656

For typeahead.js, see https://gist.githubusercontent.com/jharding/9458749/raw/bloodhound.js about how to use the $.map