Git Product home page Git Product logo

twitter-bootstrap-typeahead's Introduction

Twitter Bootstrap Typeahead Plugin Extension


UPDATE (Feb 21, 2013)

I no longer have the time to maintain this plugin. If you are looking for updated code, please take a look at the following to help you:


v1.2.2
Terry Rosen @rerrify

An extension of the Twitter Bootstrap Typeahead plugin
http://twitter.github.com/bootstrap/javascript.html#typeahead

About

All the thanks in the world to @mdo and @fat of @twitter for the wonderful Bootstrap utility.
I required more functionality out of the Typeahead plugin so I created this extension with some additional features:

  • A callback function is available for when an item is selected
  • Ability to specify data source properties
  • Ability to use a local or remote (AJAX) data source
  • Most original methods are overridable so you can customize without changing the source code

Required

  • Twitter Bootstrap 2.0+
  • jQuery 1.7+

Installation

  1. Download Bootstrap & jQuery

  2. Download this plugin.

  1. Include files in your HTML. The minimum required for this plugin are:

    <script src="/path/to/jquery.js" type="text/javascript"></script> <script src="/path/to/bootstrap-typeahead.js" type="text/javascript"></script>
  2. Execute the plugin:

    $(myElement).typeahead(options);

Events

Event Description
grepper Filters relevant results from the source.
highlighter Highlights any matching results in the list.
itemSelected The callback function that is invoked when an item is chosen.
  • item: the HTML element that was selected
  • val: value of the *val* property
  • text: value of the *display* property
lookup Determines if source is remote or local and initializes the search.
matcher Looks for a match between the query and a source item.
render Renders the list of results.
select Selects an item from the results list.
sorter Sorts the results.

Options

Name Type Default Description
ajax object
{
    url: null,
    timeout: 300,
    method: 'post',
    triggerLength: 3,
    loadingClass: null,
    displayField: null,
    preDispatch: null,
    preProcess: null
}
The object required to use a remote datasource.
See also: ajax as a string (below)
ajax string null Optionally, a simple URL may be used instead of the AJAX object.
See also: ajax as an object (above)
display string 'name' The object property to match the query against and highlight in the results.
item string '<li><a href="#"></a></li>' The HTML rendering for a result item.
items integer 8 The maximum number of items to show in the results.
menu string '<ul class="typeahead dropdown-menu"></ul>' The HTML rendering for the results list.
source object [] The source to search against.
val string 'id' The object property that is returned when an item is selected.

Basic Usage

The plugin in its simplest (realistic) form.

var mySource = [{ id: 1, name: 'Terry'}, { id: 2, name: 'Mark'}, { id: 3, name: 'Jacob'}];

$('#myElement').typeahead({
	source: mySource
});

Or using a remote data source:

$('#myElement').typeahead({
    ajax: '/path/to/mySource'
});

Examples demonstrating various options are included in this project under the /demo folder

Why did you change so much from v1.0 to v1.1?

I found certain things to be redundant, like having separate sort and display properties. I can't think of a reasonable scenerio where you would be sorting based on something different than what you are displaying.

What the $#&* did you do to the source code?

I added comments, semi-colons and other formatting that I like to use based on idiomatic JS guidelines.

If you are concerned with the bigger file size, you should always be minifying your JS before production use.

Change Log

1.2.2

  • Added support for jQuery 1.8 & Bootstrap 2.1
  • Removed usage of jQuery.browser #9385
  • Changed jQuery.data() to jQuery._data() in order to make test suite operational #11718
  • Added an undocumented function eventSupported(eventName) to verify browser support for keydown event. You may override this function if you prefer to do this check another way.

1.2.1

  • Some AJAX tests added
  • Added fix for spontaneous AJAX bug reported by users
  • grepper and lookup methods are now overridable

1.2

  • Added AJAX support

1.1

  • Major code cleanup
  • Test cases added
  • Documentation improvements

Road Map

1.3

  • Add template support

twitter-bootstrap-typeahead's People

Contributors

clj avatar nerdess avatar slobo avatar tcrosen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

twitter-bootstrap-typeahead's Issues

V2.0 blur issue

I found an issue with your blur event.

Using Chrome on Mac, Jquery 1.8.2 and latest 2.0 js as of the date of this posting. Im using an ajax based source not that it matters.

Here is where the issue occurs:

listen: function () {
this.$element
.on('blur', $.proxy(this.blur, this))
.on('keyup', $.proxy(this.keyup, this));

This blur event will sometimes fire and complete before the browser has a chance to send the click event to the typeahead list.

I found changing the timeout from 150ms to 250ms fixed the issue on my development box. Is there a better way we could write this?

AJAX results should not be filtered?

I don't know if this is correct but, when I configure an AJAX call to give results to Typeahead it is supposed that results are filtered. As typeahead searchs for the querystring in the results If one of them hasn't it then it is not displayed.

query: 'asdf' # My database object has a field with that value
result: {id: 3, name: 'John Smith'} # Not displayed because 'asdf' is not contained in 'John Smith'

I know this is issue occurs because I'm using typeahead as a classic autocomplete, but I'm sure that other users are going to use it in the same way. I've fixed this in my results appending the field where the string was found, but it would be nice if we have an option for disabling filtering when using AJAX.

Cheers,

C.

bootstrap-typeahead.js getting data from external JSON file or python flask view

Hello I have seen all the examples of the library it is really nice, but I am unable to fetch data from external JSON file or my flask view.

I am able to get Typeahead all working in this

$('#demo1').typeahead({
        source: [
            { id: 1, name: 'Toronto' },
            { id: 2, name: 'Montreal' },
            { id: 3, name: 'New York' },
            { id: 4, name: 'Buffalo' },
            { id: 5, name: 'Boston' },
            { id: 6, name: 'Columbus' },
            { id: 7, name: 'Dallas' },
            { id: 8, name: 'Vancouver' },
            { id: 9, name: 'Seattle' },
            { id: 10, name: 'Los Angeles' }
        ]
    });

but I need the source data to be fetched from external json or URL
like in the documentation listed

$('#demo4').typeahead({
        ajax: '/cities/list'
    });

I am putting my sample.json file in /cities/list/sample.json .but it is not showing the expected results. Even the working examples listed does not use effective JSON. What to do to enable external JSON.

I have asked this question on SO also here is the link please have a look
http://stackoverflow.com/questions/19895916/bootstrap-typeahead-js-fetch-json-from-a-file-or-remote-source

unexpected non-whitespace character after JSON data

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
[Break On This Error]

this.options.itemSelected(JSON.parse($selectedItem.attr('data-value')));

Bootstrap 2.2.1

    $('#q').typeahead
      source: '/admin/search.json'
      val: '_id'
      #tmpl: _.template("<li id=\"<%= _id %>\"><a href=\"/admin/reviews/<%= _id %>\"><%= name %>, sdfsdf<%= reviewable_type %></a></li>")
      minLength: 3
      itemSelected: ->
        alert "Congratulations you used everything!"

When I try to use the template, I can see the URL links are correct but when I click it, I get the same error and no redirect.

json

[{"_id":"4f956b76d97ab00001000027","reviewable_type":"City","name":"Krak\u00f3w"},{"_id":"4ff94b8725b1a80001000006","reviewable_type":"Place","name":"Bomba"},{"_id":"4fe056caa9e05f0001000030","reviewable_type":"Place","name":"Singer"},{"_id":"50a8286ddced86b247000014","reviewable_type":"Place","name":"Burgermeister"},{"_id":"4fddff698fdfdf0001000009","reviewable_type":"Place","name":"Miejsce"},{"_id":"4f7efda4a660a20001000022","reviewable_type":"Place","name":"Plan B"},{"_id":"4f8c506018e6d3000100000a","reviewable_type":"Place","name":"Propaganda"},{"_id":"4fe188af4e8f460001000007","reviewable_type":"Place","name":"Alebriche"},{"_id":"4f7ec8231c3f30000100002d","reviewable_type":"City","name":"Montreal"},{"_id":"5011352f6f98860002000004","reviewable_type":"Place","name":"Charlotte: Chleb i Wino"}]

Accent Insensitive Highlighting

I'd love for accent insensitive highlighting to be baked in the same way case insensitivity is. I'm currently using the following for French, and I'm not sure how it would generalize:

highlighter: function(item) {
  var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
  // French accent insensitivity
  // ---------------------------------------
  query = query.replace(/a/i, '[aáÁàÀâÂäÄ]');
  query = query.replace(/e/i, '[eéÉèÈêÊëË]');
  query = query.replace(/i/i, '[iíÍìÌîÎïÏ]');
  query = query.replace(/o/i, '[oóÓòÒôÔöÖ]');
  query = query.replace(/u/i, '[uúÚùÙûÛüÜ]');
  query = query.replace(/c/i, '[cçÇ]');
  // ----------------------------------------
  return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
    return '<strong>' + match + '</strong>';
  });
}

Data is not parsed

Ajax doesnt work cause data received from server is not parsed.

ajaxLookup: function (data) {
var items;

        this.ajaxToggleLoadClass(false);

        if (!this.ajax.xhr) return;

        if (this.ajax.preProcess) {
            data = this.ajax.preProcess(data);
        }

        // Save for selection retreival
        this.ajax.data = data; // data must be parse as JSON => JSON.parse(data);

        items = this.grepper(this.ajax.data);

        if (!items || !items.length) {
            return this.shown ? this.hide() : this;
        }

        this.ajax.xhr = null;

        return this.render(items.slice(0, this.options.items)).show();
    },

Suggest for templating

Hi,

I really liked your fork.

I read your idea for templating, and want to give you my two cents.

I wouldn't force the use of a template engine (I like Underscore.js, but I also like Twig.js).

Suggestion:

$('#my-element').typeahead({
    source: [{ id: 1, name: 'Toronto' }, { id: 2, name: 'Montreal' }, { id: 3, name: 'New York' }],
    templater: typeahead, // or underscore, or twig

});

Then the render method could call any of externals template engines (underscore, twig) or a simple internal "templater" that just uses variable replacement with a pattern or regex.

[]'s
Rafael Goulart from Brazil

AJAX request dont work

Hi,
at first I want to thank you for your great job,
but I have problem and I cannot figure it out.

This is what Ive got:

$('#job-find').typeahead({
        ajax: cakeRoot+'jobFind/getList'
});

when I type "Job" plugin send AJAX request successfully, response:

[{"id":"1","name":"Job 1"}{"id":"2","name":"Job 2"}{"id":"3","name":"Job 3"}]

but Nothing showed, firebug writes an error:

TypeError: items is null
if (!items.length) {...
in bootstrap-typeahead.js :181

content type of response is application/json
I dont know how to fix it.
please help me.

Minified Version

I love your plugin, to better please create a minified version!

PRe selecting a value.

I see that on the old version you could select an item on load.

I cant see to find this possibility on the v2.
Can we still do this ?

To make it a bit cleared on what i am looking for.
I want when the page loads, to automatically select an item on the list, and fire the ajax that is already done when the itemSelected is done.

Local key value cache of entries and results

Any thought or focus on having each of the typeahead elements cache their search results into a local cache of search values and results? This might speed up the UI if the object has a preloaded cache of common values, or simply keeps track of what it has shown the user.

Allow selecting user input if there are no results

Hello,

I was wondering if there was any interest in allowing the user to still select the input they put in if there are no matching results.

I was thinking I'd add the user input as the very last element in the render function.

What do you think? I need something like this so let me know and I'll try to write up a patch.

crach on ajax.timerId = setTimeout

setTimeout crash when the argument is not a funcion or a string, in this case:

// Query is good to send, set a timer
this.ajax.timerId = setTimeout($.proxy(that.ajaxExecute(query), this), this.ajax.timeout);

so I had to do like this to fix it:

// Query is good to send, set a timer
this.ajax.timerId = setTimeout(function() {
    $.proxy(that.ajaxExecute(query), this)
}, this.ajax.timeout);

bootstrap 2.2.1 support?

hi, nice extension!
I tried using it with bootstrap 2.2.1 inside a


the functionality works fine, but it no longer scrolls with the container as expected.

selecting dropdown entries by keyboard skips every second entry

I'm viewing the 'Twitter Bootstrap Typeahead Extension Demo' v1.2.2 form my local file system. In Firefox 14.0.1 and Opera 12.00 it is only possible to select every second entry of the search results in the dropdown. In detail:

  1. Open demo.html site
  2. Enter 'r' into the first typeahead example
  3. The list now display following hits:
  4. Toronto (selected)
  5. Montreal
  6. New York
  7. Vancouver
  8. Press arrow down key once:
  9. Toronto
  10. Montreal
  11. New York (selected)
  12. Vancouver
  13. Press arrow down key one more time:
  14. Toronto (selected)
  15. Montreal
  16. New York
  17. Vancouver

In Chrome it works as expected.

catched a error

Uncaught TypeError: Cannot call method 'toLowerCase' of undefined.

has anybody met it?

Cannot set itemSelected callback in element data attributes

This may be by design, or not even possible, but the way I generate my html and javascript it would be much cleaner to set all of the options for my typeahead in the text field's data attributes. I can set other option (like source, display) but not the callback.

This is what I want to do;

<input id='my_awesome_text_field' data-provide='typeahead' data-display='color' data-source='[{color:'blue'},{color:'red'},{color:'green'}]' data-itemSelected='function () {alert('itemSelected callback!')}'>

This is an awesome extension otherwise though - thanks!

twitter bootstrap typeahead 2.0.4 ajax error

I have the following code which definitely returns a proper data result if I use the 2.0.0 version, but for some reason bootstrap's typeahead plugin is giving me an error. I pasted it below the code sample:

$('#test').typeahead({
source: function(typeahead, query) {
return $.post('/Profile/searchFor', { query: query }, function(data) {
return typeahead.process(data);
});
}
});
When I run this example I'm getting a jQuery bug that says the following:
Error line 104: return item.toLowerCase().indexOf(this.query.toLowerCase())

Any thoughts? ... The same code works in the 2.0.0 version of the plugin.

Is it possible to catch an event when typeahead field is emptied or no match is found?

And if not do you think it's possible to add feature for this.

What I would like implement is a standard select like typeahead, where the user can only select values form the source.

Next to that I need to catch an event if the typeahead is emptied as based on the selection I'm setting some other values. Think of source is a product catalog, where after selecting an item the price is also retrieved from the source and stored in another field.

Passing parameters?

I can't figure out how to pass parameters with POST. Normally, I would use something like
data: { 'param1': val1, 'param2' : val2 }, but that doesn't seem to work.
I suppose can use GET and than pass a bunch of parameters in the URL, but I'd rather stick with POST.

Request - How about converting this to an AMD module?

Sorry for putting a request in the issues but I'm not sure else where to put it.

This is awesome, btw.

Is there any chance you can convert it to an AMD module to use with something like Require.js?

I would but I'm too much of a newb :(

Edit:

I think I'm going to try doing something similar this twitter bootstrap AMD'ified regular bootstrap module fork:
liamks/bootstrap@7b10dd9

I'll let you know if it works!

Object inside object

Is possible get object inside array in json response?

Example:

{"success":true,"message":null,"messages":null,"data":[{"id":"109","name":"Bruno \u00c1vila"},{"id":"106","name":"Bruno Batista"},{"id":"107","name":"Bruno Batista"}]}

Returning data

line 156: this.ajax.xhr = jAjax(this.ajax.url, params, $.proxy(this.ajaxLookup, this), "json");
Not only html please.

Invalid argument when using AJAX

Hi - firstly, thank you for this - it's fantastic.

I just started using the new version, however, and got the same error reported elsewhere:

I get an Invalid Argument error on this line (line 30, column 13):

        this.ajax.timerId = setTimeout($.proxy(that.ajaxExecute(query), this), this.ajax.timeout);

My script is:

$('.agents').typeahead({
    ajax: {url:'/api/analyst',method:'get'},
    itemSelected: displayResult
});

As soon as I click on Continue in VS, the drop down list briefly appears (<1sec) then disappears again (so I know the JSON is being returned).

The ajax call is returning JSON:

[{"id":4,"name":"Tait, Mark"},{"id":11,"name":"Smith, James"}.......]

Thank you for any help you may be able to provide.

Mark

Running IE9 with VS11 debug mode, errors in $.proxy

I don't think this is a real issue, but I get an error on this line "this.ajax.timerId = setTimeout($.proxy(that.ajaxExecute(query), this), this.ajax.timeout);" - line 130 when I start the web in debug mode in VS11. This halts my script from further execution.
However, running the site without debugging, the typeahead script works just fine.
I just want to confirm if this is an issue with VS11 that tries to run through the script and thus mess up the context of the function when debugging?

Example on the Readme is wrong

Written as

$(function() {
    $('#myElement').typeahead({
        //...
        itemSelected: function(val) {
            alert('You selected the city ' + text + ' with ID ' + val)
            console.log(item)
        }
    })
})

when it should be written as

$(function() {
    $('#myElement').typeahead({
        //...
        itemSelected: function(item, text, val) {
            alert('You selected the city ' + text + ' with ID ' + val)
            console.log(item)
        }
    })
})

Please add a license

Please add a license. We are using 1.2.2, but I can't find a license anywhere.

v2.0.0 itemSelected js error

Uncaught SyntaxError: Unexpected token r bootstrap-typeahead.js:205
Typeahead.select bootstrap-typeahead.js:205
Typeahead.click bootstrap-typeahead.js:304
p.isFunction.f jquery-1.8.2.min.js:2
p.event.dispatch jquery-1.8.2.min.js:2
g.handle.h

On line 205:
this.options.itemSelected(JSON.parse($selectedItem.attr('data-value')));

I'm getting this on every browser.

Demo how to chain two typeahead fields

Hi,

is it possible that you update demo to show how to chain two typeahead input fields?

I want to have one input field to fetch e.g. Manufacturers and second one should fetch only models but URL for 2nd ajax should be restricted with param manufacturerId fetchd in previous step.

I hope that I sound clear enough :)

Thank You

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.