Search code examples
javascriptjquerytwitter-bootstrapbootstrap-typeaheadbootstrap-tags-input

Integrating Bootstrap 3 Typeahead with Bootstrap Tagsinput


I'm trying to integrate the Bootstrap 3 Typeahead plugin (basically a port from the old Bootstrap typeahead functionality before it was removed in Bootstrap 3, if I understand correctly) with the Bootstrap-Tagsinput plugin.

I have no problem getting these to work individually, including the JSON prefetch typeahead functionality. I do not understand how to integrate the two. I don't think it should be too hard but my knowledge of Javascript is apparently lacking.

Here is my input field:

<input type="text" id="tagFilter" data-provide="typeahead" data-role="tagsinput">

And here is the way the typeahead plugin is called in Javascript:

//The typeahead
$.get('tags.php', function(data){
    $("#tagFilter").typeahead({ source:data });
    },'json');

If it's helpful, the Tagsinput has an example in its docs explaining how to implement twitter typeahead.js:

$('input').tagsinput();

// Adding custom typeahead support using http://twitter.github.io/typeahead.js
$('input').tagsinput('input').typeahead({
  prefetch: 'citynames.json'
}).bind('typeahead:selected', $.proxy(function (obj, datum) {  
  this.tagsinput('add', datum.value);
  this.tagsinput('input').typeahead('setQuery', '');
}, $('input')));

But I'm using a different plugin. I found that one to be over my head.

Thanks again.


Solution

  • Okay...so I've actually decided on using the Twitter typeahead.js, as I managed to get it working. I used the following code, please someone point out if it's not the best way to do it.

    <input type="text" id="tagFilter" data-provide="typeahead" value="test,arlington">

    $('#tagFilter').tagsinput({
        typeahead: {
           source: $.get('tags.php')
        }
        });
    

    My tags.php file is just a list, I think it will take a lot more work to get this to function with an associative array with keys in the JSON file. I decided there was no benefit to this in my case, as I'm only concerned with the tag names for query purposes.

    So my tags.php is just echoing the result of:

    //the mySQLi query is above...
    while ($row = mysqli_fetch_assoc($result)) {
            $tags[] = $row['tag_name'];
    
        }
    echo json_encode($tags);
    

    Hope someone can benefit.