twitter / typeahead.js Goto Github PK
View Code? Open in Web Editor NEWtypeahead.js is a fast and fully-featured autocomplete library
Home Page: http://twitter.github.io/typeahead.js/
License: MIT License
typeahead.js is a fast and fully-featured autocomplete library
Home Page: http://twitter.github.io/typeahead.js/
License: MIT License
Hi !
Could remote call url depends on another value, such as another input field value ?
It works once, but then the url doesn't change on that value change.
Thanks a lot !
Who knows, maybe not everyone wants the hint.
This wrecked my head all day yesterday. My textbox has a background which changes on focus. Typeahead doesnt inherite this when it creates .tt-hint and I couldnt fix it in css because there is no before sibling selector in css. Eventually I just wrote the solution with jQuery.
$(function(){
$(".tt-query").focus(function(){
$(".tt-hint").addClass('focusclass');
}).blur(function(){
$(".tt-hint").removeClass('focusclass');
});
});
.focusclass { background: #f5f5f5 !important; -webkit-box-shadow: none; -moz-box-shadow: none; -ms-box-shadow: none; box-shadow: none; }
Look at http://jsfiddle.net/yADJz/
It seems we have a problem with padding/margin, or whatever ๐
Thoughts?
I know that is not a real issue because the tokens must not be formatted this way.
But anyway,
{
value: "test",
tokens: [
'test', 'foo', '', 'bar'
]
}
Situation
The tokens are setted, but there is an empty key in it
Action
user click for the first time in the input, nothing bad happen
user type something, backspace everything until no letter left
Result
all ""
token are matched, placeholder is displayed again but above the autocompletion.
And now everytime the user click(focus) in the input, the autocompletion is shown.
Again, it's a mistake made by the developper (me in this case) so it's not a real issue but it could also be an intersting wildcard if it was displayed on the first click and without the placeholder bug :)
There are some big accessibility problems in:
http://twitter.github.com/typeahead.js/examples/
Just run it through http://wave.webaim.org/
Anyways, these should be fixed so that it's easier to see when the problems are with the JS and when they are with the formatting of the HTML.
Manual testing is also going to be required.
Because of preventDefault
, shift-up/down don't properly highlight and select input text, and alt/cmd-up/down don't properly let the cursor move to the beginning and end of the field.
Hi guys, I started to try the library today, and testing with a simple remote dataset, I came with this jquery error:
TypeError: invalid 'in' operand e
After a quick check, I realized that the error is triggering on the onSuccess callback of the ajax call of the get method, this line:
cb && cb(resp);
I'm missing something? Working with jquery 1.9.1 and typeahead.js,
When typeaheads gain focus and no query has been entered yet, should we support default top suggestions? I could see how this could be useful.
You can sort of do this with the current implementation of typeahead.js by using ''
as a token. It's a little buggy though because the hint is shown and it overlaps with the placeholder.
The following datum won't be found when typing 'course-106' into typeahead:
{
label: "Course-106: Twitter Typeahead"
value: "course106",
tokens: [
"course-106:",
"twitter",
"typeahead"
]
But it appears that one could customize the tokenizeText function to support this:
tokenizeText: function(str) {
//return $.trim(str).toLowerCase().split(/[\s\-_]+/);
return $.trim(str).toLowerCase().split(/[\s_]+/);
}
Consider adding a configuration option so that users can provide customized regular expression for tokenizedText unless there's a better solution.
Use case: I am using an existing API to fetch data for the typeahead. The data from the API does not contain a key called "value". It does however have another meaningful key called "name" I would like to use.
Suggestion: To have a property where we can set the value key, so we do not have to write wrappers for existing API's.
$(element).typeahead([{
name: 'source1',
remote: '/api/search?q=%QUERY',
valueKey: 'name'
}]);
Typehead drop down width not expanding as per the length of items in suggestion list.The suggestion text just pops out of the drop down.
If the remote returns something where the dataset is nested, you can't extract the dataset from it. It would also allow to customise the call to the backend if some extra headers were to be set.
Would it be possible for there to be an option for the first item to be automatically selected in the typeahead on search so a press of the enter key will go to that specific item's url? This would save the user needing to press the downarrow key to get to that first item and then pressing the enter key. Thanks!
Hi,
I found a litte problem with the placeholder when deleting letters from selection.
To reproduce:
Now the placeholder is visible in the back and is aligned left, while the input is aligned right.
regards
I was a bit surprised to see the lack of a default template engine. I know you can add an extra dependency on handlebars or so.
Maybe a good start:
element.typeahead(
template: '<p>$name ($code)</p>',
remote: '/api?value=%QUERY',
engine:
compile: (template) ->
return {
render: (ctx)->
return template.replace(/\$(\w+)/g,
(msg) -> ctx[msg.substring(1)]
)
}
)
We have data coming back from the server that looks as follows...
{
"status": "success",
"keyword": "s",
"data": {
"suggestions": [
{
value: 'unitedAirlines',
tokens: ['united', 'airlines'],
name: 'Jake Harding',
},
{
value: 'deltaAirlines',
tokens: ['delta', 'airlines'],
name: 'Jake Harding',
}
}
}
The question is how to I tell typeahead.js
to get the suggestions
data.
"Twitter Typeahead" => "typeahead.js"
Script gets executed when given as an option
$('#sampleauto').typeahead({
name: 'accounts',
local: ['github', 'select2', 'typeahead', '<script>alert("github")</script>']
});
Hello,
typeahead.js won't minify using Google Closure Compiler, due to errors in code (36 for 0.8.1).
I used this to test :
http://closure-compiler.appspot.com/home
Thanks !
We should do this eventually:
Here is my data items returned from server -
[{
"tokens": ["Python"],
"name": "Python",
"value": "python",
"id": "1"
}, {
"tokens": ["PHP"],
"name": "PHP",
"value": "php",
"id": "2"
}, {
"tokens": ["Ruby"],
"name": "Ruby",
"value": "ruby",
"id": "3"
}, {
"tokens": ["Scala"],
"name": "Scala",
"value": "scala",
"id": "4"
}, {
"tokens": ["HTML"],
"name": "HTML",
"value": "html",
"id": "5"
}, {
"tokens": ["HTML5"],
"name": "HTML5",
"value": "html5",
"id": "6"
}, {
"tokens": ["JavaScript"],
"name": "JavaScript",
"value": "javascript",
"id": "7"
}, {
"tokens": ["CSS"],
"name": "CSS",
"value": "css",
"id": "8"
}, {
"tokens": ["CSS3"],
"name": "CSS3",
"value": "css3",
"id": "9"
}]
And initializing like -
<script type="text/javascript" src="{{ STATIC_URL }}js/vendor/hogan-2.0.0.js"></script>
<script type="text/javascript" src="{{ STATIC_URL }}js/vendor/typeahead.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#skills').typeahead([
{
name: 'inhouse',
prefetch: '{% url ajax-skills %}',
remote: '{% url ajax-skills %}?q=%QUERY',
template: '<strong>{{id}}</strong>',
engine: Hogan
}
]);
});
</script>
jQuery has been loaded above these. The problem is, the template
option is not being rendered properly. For the above case, all it generates is empty strong
elements. and if I don't put any html tag inside the template
option, it just takes the value
field from the received data and acts on it's own and ignores whatever I've written inside the template
field. What is the problem?
PS: And even though I've put all those data in prefetch
, it calls the server on every keypress. It shouldn't, right?
Loading only typeahead.js > loading both typeahead.js and typeahead.css
Go to the example demo page,
$('input[placeholder="countries"]').val('France').click().blur(); the input value is now blank.
If you set a value, you would like to keep it no ? (I would)
Same problem if the input contains a value before becoming a typeahead input.
Currently, it looks like typeahead.js has a hard dependency on jQuery. Are there any specific reasons that this is the case, or is it reasonable to assume that one might be able to use something like Zepto in the future instead?
If the latter, are there any plans for doing so presently?
Would be nice to have the option to automatically submit form when someone clicks on suggestion or presses return
Maybe something similar to what Bootstrap's typeahead offers.
Hi guys, I've a strange problem with rendering the template for my remote data (I'm using Hogan).
Let's say I have this JSON data returned from the server:
var data={"companies": [{"id": "1", "name": "Twitter", "value": "twitter"}, {"id": "2", "name": "Facebook", "value": "facebook"}]}
And I have this template:
var text="{{#companies}}{{name}}{{/companies}}{{^companies}}'No companies!'{{/companies}}"
If I run Hogan within the browser console, it renders the data correctly:
tpl=Hogan.compile(text)
tpl.render(data)
=> "TwitterFacebook"
BUT if I use typeahead, with the same template and Hogan as the engine, it gives me "No companies!" and no completion.
$("input[name='query']").typeahead({
name: 'search',
remote: '/search.json?query=%QUERY',
template: [
'{{#companies}}',
'{{name}}',
'{{/companies}}',
'{{^companies}}',
'No companies!',
'{{/companies}}'
].join(''),
engine: Hogan
})
To be sure that typeahead is working, I returned a plain datum array and changed the template accordingly:
{
"name": "Twitter",
"value": "twitter"
}
{
"name": "Facebook",
"value": "facebook"
}
and it worked good, giving me result list and completion.
What I'm missing?
Hi !
Same data (simple string array) works with remote and local, but not with prefetch.
["Corse","Alsace","Vall\u00e9e de la Loire","Jura \/ Savoie","Provence","Languedoc - Roussillon","Beaujolais","Sud Ouest","Bourgogne","Bordeaux","Champagne","Vall\u00e9e du Rh\u00f4ne"]
JS error in isArray, in jquery.min.js.
TypeError: invalid 'in' operand e
Using JQuery 1.9.1
Any idea ? Thanks !
Maybe you can do this now, but I have been looking at it for a few hours .... I would like to integrate this search bar into a dashboard I have that is rendering a series of results via backbone.js. I have it working now, but it would be nice to provide a callback to type to do the filter on: click, dropdown, etc.
Can we have a callback function for template ? I had something like this in mind:
template: function(datum) {
if( datum.isCustomer )
return '<p class="someClass">Customer: ' + datum.customer + '</p>';
else
return 'Nope...';
}
This would allow the use of "if/else/while/for" and other conditional statement to render the results.
The same would be awesome for an "onSelection" event:
onSelection: function(datum) {
if( datum.isCustomer )
alert(datum.customer + ' has been selected !');
else
alert('Something else has been selected my son !');
}
Finally, if we could provide a function for the remote option, it would allow us to use our own way to send the AJAX request. Let's say:
remote: function() {
var jsonResult = mySuperAjaxLibrary.send('http://ajax.somesupersite.net/search.php');
return jsonResult;
}
If you make this happen, I love will you forever.
Thank you and pardon my poor english.
Since typeahead.js is generated from the files in src/ and isn't checked in, how are we supposed to define our Bower component? Do we need a shim repo? Do we just bite the bullet and check in typeahead.js (I'd rather not)?
@sindresorhus, any suggestions?
When the dalatist present some word starting by an upper case letter, the user type in lowercase and complete it with tab, the first letter will not be changed but the rest of the word is still well completed (I mean with upper case)
ie:
data given = Coca-Cola
data typed = co
user do tab
data displayed = coca-Cola
Don't know if it's a real issue but it's a bit annoying. Doesn't occur with other shortcut.
In the best picture winners example, typeahead is configured like this:
$('.example-films .typeahead').typeahead([ { name: 'best-picture-winners', remote: '../data/films/queries/%QUERY.json', prefetch: '../data/films/post_1960.json', template: '<p><strong>{{value}}</strong> โ {{year}}</p>', engine: Hogan } ]);
If I enter "b", it issues a network request to
http://twitter.github.com/typeahead.js/data/films/queries/b.json
for which the response is
[ { "year": "1928/1929", "value": "The Broadway Melody", "tokens": [ "The", "Broadway", "Melody" ] }, { "year": "1935", "value": "Mutiny on the Bounty", "tokens": [ "Mutiny", "on", "the", "Bounty" ] }, { "year": "1946", "value": "The Best Years of Our Lives", "tokens": [ "The", "Best", "Years", "of", "Our", "Lives" ] }, { "year": "1957", "value": "The Bridge on the River Kwai", "tokens": [ "The", "Bridge", "on", "the", "River", "Kwai" ] }, { "year": "1959", "value": "Ben-Hur", "tokens": [ "Ben-Hur" ] } ]
Good.
Now if I delete the 'b' from the input, typeahead issues a request to:
http://twitter.github.com/typeahead.js/data/films/queries/.json
Which comes back with a 404. If there isn't a way to prevent this request, this is a bug.
I'd appreciate a general callback so i can find out when typeahead is initialized and done prefetching etc.
For example:
$("input").typeahead({
name: 'description',
prefetch: 'search.json',
limit: 1000,
callback: function(){
alert("Typeahead is ready for you!");
}
});
What is the recommended approach for re-initializing typeahead to change a prefetch, a dataset, or some other property?
I don't know why i am getting this error, this is my code. I am using Rails 4 if that matters.
$('.typeahead').typeahead(
name: 'exercises',
local: ['Bench Press', 'Darm', 'Barm'],
);
Currently this plugin runs and initializes as soon as its called, even if the input was never interacted with, This adds overhead for memory etc.
How about allowing the option initializeOn:"keypress"
which will all initializing functionality only upon provided (optional) option.
This way users has full control on initializing only on first interaction (how the user wants to define that)
Currently, this can be achieved as following:
$("#inputEle").one(function("input"){
$("#inputEle").typeahead(options).trigger("input");
});
A typeahead input is wrapped with some additional markup by this code:
return $input.attr({
autocomplete: false,
spellcheck: false
}).addClass("tt-query").wrap(html.wrapper).parent().prepend($hint).append(html.dropdown);
The boolean false
values are converted to the string "false"
by jQuery. However, Chrome and Safari (and perhaps other browsers as well) will still autocomplete on the field, because the autocomplete
attribute actually should be set to the string "off"
per spec.
The same problem with this attribute occurs on the tt-hint
input's markup.
Hi,
localStorage doesn't seem to be refreshed when json changed, when using prefetch.
Thanks !
For prefetched data, tokens get lowercased, but that's not happening for local data. Here's an example. This is definitely needs to be fixed for v0.8.1, @timtrueman, @vskarich can one of you take care of this?
Thanks @rmosolgo for finding this bug.
Hi,
i'd appreciate a method i could call, so typeahead would init, pull in the defined json, do the search and present the results.
Currently i do this with a hack: $("input.typeahead").trigger("input");
Some background on why i'd find this useful:
im am trying to use typeahead.js not only for suggestions but for a complete search engine.
My goal is to offer the user suggestions while he types into the input field and then, once hits the return key, i'll load a searchresults page and display a complete list of all matches. The search results page pre populates the input field with from a parameter in the query string, wires the field up with .typeahead and would then need to call a method so typeahead will do its magic and display the results (which i reformat with jquery so they'll not be attached to the input field any longer).
It would be nice to have a simple way to set a custom callback when a suggested item is selected.
I expect something like:
selectCallback : function(typeaheadItem, selectedItem){ .... }
where
This way it would be easier to user other properties/attributes of the selected item (not only the value property) when something is selected.
Updated the my data (.json) with new data, but it still uses the old data if I enter somethign in the search, and if I change the js code it will stop working and give me an syntax error in the jquery core. I cleared the cache a couple of times but it wont work.
I am using it in firefox and local.
I was trying out the examples where a json is prefetched, so I first tried a static json file served with nginx. I got the error:
"Uncaught TypeError: Cannot use 'in' operator to search for '123' in"
It turns out that the default nginx configuration doesn't send a correct json type.
Adding
application/json json;
to mime.types
of nginx solved the problem.
I am not sure whether this is a bug in nginx, jquery or typeahead, but just wanted to document it in case someone else comes across this.
A sample project that demonstrates the bug is here: https://dl.dropbox.com/u/83342/nginxbug.zip
There's a handful of issues asking for something along the lines of a "selection callback". While I agree this is necessary, I don't think adding an option like onSelection
is the best way to go about it. Instead, I think triggering custom events on the typeahead input is the way to go. It's a more extensible approach and it won't pollute the options hash.
I'm creating this ticket to start brainstorming what events we need to trigger. The only 2 I can think of right now are:
If there's anything else you'd like an event triggered for, leave a comment in this issue.
Anyway to group results by categories? It would be nice to show the category name and list the items below it.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.