Skip to content

Instantly share code, notes, and snippets.

@geuis
Created February 16, 2012 22:58
Show Gist options
  • Star 46 You must be signed in to star a gist
  • Fork 25 You must be signed in to fork a gist
  • Save geuis/1848558 to your computer and use it in GitHub Desktop.
Save geuis/1848558 to your computer and use it in GitHub Desktop.
Remote data querying for Twitter Bootstrap 2.0 Typeahead without modifications
<script>
// Charles Lawrence - Feb 16, 2012. Free to use and modify. Please attribute back to @geuis if you find this useful
// Twitter Bootstrap Typeahead doesn't support remote data querying. This is an expected feature in the future. In the meantime, others have submitted patches to the core bootstrap component that allow it.
// The following will allow remote autocompletes *without* modifying any officially released core code.
// If others find ways to improve this, please share.
var autocomplete = $('#searchinput').typeahead()
.on('keyup', function(ev){
ev.stopPropagation();
ev.preventDefault();
//filter out up/down, tab, enter, and escape keys
if( $.inArray(ev.keyCode,[40,38,9,13,27]) === -1 ){
var self = $(this);
//set typeahead source to empty
self.data('typeahead').source = [];
//active used so we aren't triggering duplicate keyup events
if( !self.data('active') && self.val().length > 0){
self.data('active', true);
//Do data request. Insert your own API logic here.
$.getJSON("http://search.twitter.com/search.json?callback=?",{
q: $(this).val()
}, function(data) {
//set this to true when your callback executes
self.data('active',true);
//Filter out your own parameters. Populate them into an array, since this is what typeahead's source requires
var arr = [],
i=data.results.length;
while(i--){
arr[i] = data.results[i].text
}
//set your results into the typehead's source
self.data('typeahead').source = arr;
//trigger keyup on the typeahead to make it search
self.trigger('keyup');
//All done, set to false to prepare for the next remote query.
self.data('active', false);
});
}
}
});
</script>
<input type="text" id="searchinput" data-provide="typeahead">
@adrianhove
Copy link

This might be of no consequence, however I found a way to get the clicked item value.

Here is my fork
https://gist.github.com/2297184

@geuis
Copy link
Author

geuis commented Apr 4, 2012

@zastava2012 Did you find a solution to your double-return problem? If not, do all characters entered require the double-return conversion, or is it a mixture of some characters are single-return, and others are double-return?

If you look at the character encoding values for the double-return characters, do they exist within an explicit range? If so, you could add a check that says "if this character is in range THIS to THAT, require an extra return".

@markonsn
Copy link

Hi..Can someone help me? .. I have a form with this:

<input type="hidden" id="mid" name="mid" value="" >
<input type="text" id="full_name" name="full_name" data-provide="typeahead" >

in the javascript file:

$('#full_name').typeahead().on("keyup", function(ev) {
    ev.stopPropagation();
    ev.preventDefault();
    if ($.inArray(ev.keyCode, [40, 38, 9, 13, 27]) === -1) {
      self = $(this);
      self.data("typeahead").source = [];
      if (!self.data("active") && self.val().length > 0) {
        self.data("active", true);
         $.getJSON('/medical_records/list.json', {
          q: $(this).val()
        }, function(data) {
          var arr, i;
          self.data("active", true);
          arr = [];
          i = data.length;
          while (i--) {
            arr[i] = data[i].name;
          }
          self.data("typeahead").source = arr;
          self.trigger("keyup");
          self.data("active", false);
        });
      }
    }
  });

the JSON response is correct and is:

[{"mid":4,"name":"BILL GATES"},{"mid":12,"name":"STEVE JOBS"},{"mid":20,"name":"LINUS TORVALDS"}]

.typehead() is works fine, but I want assign the 'mid' value of JSON to 'mid' input hidden.. is posible this?

I was using jquery autocomplete() and it worked but I want to use typehead()

jQuery(function() {
    return $('#full_name').autocomplete({
      source: $('full_name').data('autocomplete-source'),
      select: function(event, ui) {
        $('#full_name).val(ui.item.name);
        $('#mid').val(ui.item.mid);
        return false;
      }
    });
  });

Thanks..

@burnz
Copy link

burnz commented Jun 15, 2012

@adrianhurt take a look at my fork...

https://gist.github.com/2935906

@adrianhurt
Copy link

@burnz, thanks a lot! It works perfectly.

@mounirmesselmeni
Copy link

@burnz Thanks a lot very helpful !

@pushpinderbagga
Copy link

thanks for the code - it works albeit it sure breaks at times. I use it as below but when correcting the query - it just doesn't work.

    .on('keyup', function(ev){

ev.stopPropagation();
ev.preventDefault();

//filter out up/down, tab, enter, and escape keys
if( $.inArray(ev.keyCode,[40,38,9,13,27]) === -1 ){

    var self = $(this);

    //set typeahead source to empty
    self.data('typeahead').source = [];

    //active used so we aren't triggering duplicate keyup events
    if( !self.data('active') && self.val().length > 0){

        self.data('active', true);

        //Do data request. Insert your own API logic here.
        $.getJSON($baseLocation+"updatejs?callback=",{
            term: $(this).val()
        }, function(data) {

            //set this to true when your callback executes
            self.data('active',true);

            //Filter out your own parameters. Populate them into an array, since this is what typeahead's source requires
            arr = [],
                i=data.length;
            while(i--){
                arr[i] = data[i].name
            }

            //set your results into the typehead's source
            self.data('typeahead').source = arr;

            //trigger keyup on the typeahead to make it search
            self.trigger('keyup');

            //All done, set to false to prepare for the next remote query.
            self.data('active', false);

        });

    }
}

});


@tcgumus
Copy link

tcgumus commented Nov 3, 2012

The function doesn't go in after
"var autocomplete = $('#searchinput').typeahead().on('keyup', function(ev){"

What did i do wrong? i downloaded the code but didnt work for me. Should i install an extra reposity?
Thank you.

@CristianDeluxe
Copy link

Thanks for your work and sorry for my English.

Here my modifications for my own requirements: You can set the url in input using "data-link", useful if you have lot of differently autocomplete sources.

    // Disable browser autocomplete
    $('.typeaheadlink').attr('autocomplete','off');

    var autocomplete = $('.typeaheadlink').typeahead()
        .on('keyup', function(ev){

            ev.stopPropagation();
            ev.preventDefault();

            //filter out up/down, tab, enter, and escape keys
            if( $.inArray(ev.keyCode,[40,38,9,13,27]) === -1 ){

                var self = $(this);

                // We get the URL from input
                var urljson = self.attr("data-link");

                //set typeahead source to empty
                self.data('typeahead').source = [];

                //active used so we aren't triggering duplicate keyup events
                if( !self.data('active') && self.val().length > 0){

                    self.data('active', true);

                    //Do data request.
                    $.ajax({
                        url: urljson,
                        type: 'get',
                        data: {q: $(this).val()},
                        dataType: 'json',
                        success: function(data) {

                            //set this to true when your callback executes
                            self.data('active',true);

                            //set your results into the typehead's source 
                            self.data('typeahead').source = data;

                            //trigger keyup on the typeahead to make it search
                            self.trigger('keyup');

                            //All done, set to false to prepare for the next remote query.
                            self.data('active', false);
                        }
                    });

                }
            }
        });
<input name="myautocompleteinput" class="typeaheadlink" data-provide="typeahead" data-items="4" data-link="http://domain.com/mydata.php" maxlength="255" type="text" id="myautocompleteinput">

Maybe this can be useful for someone.
Thanks again!
Cris

@rahulcs
Copy link

rahulcs commented Mar 21, 2013

Worked Like a charm :) Thank you :)

@hamzakc
Copy link

hamzakc commented Jul 11, 2013

Thanks for writing this up. It has helped me a lot. However I would recommend using the official twitter typeahead library and not the one that comes packaged with bootstrap.js. It allows you to do a lot more and has remote lookups built in. You can find it here

http://twitter.github.io/typeahead.js/

The api is different to the one packaged into bootstrap. I just downloaded a custom version of bootstrap and removed typeahead and started using the lib above. It seems much more flexible :)

Thanks

Hamza

@chiragdhori
Copy link

hi is there any full document available for yii bootstrap type ahead from database . i have to retrieve data from data from data base.but there is no documentation available anywhere. while i tried for that but not found anywhere..

i have to find patient name form data base but not able find that name.form that..wheater key event is working or ajax call is not working i dnt get the solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment