Modify the data returned by a promise? - javascript

i am current using this plugin for tags-input 'bootstrap-tagsinput'
i am trying to use the typeahead feature provided by this plugin.
the source attribute in typeahead expects a promise to be returned.but i need to modify the returned data. How do i do this?
$('input').tagsinput({
typeahead: {
source: function(query) {
return $.get('/tags.json').then(function(data){
return _.pluck(data.tags,'keyword');
});
}
}
});

Try
var list = ["Amsterdam", "Beijing", "Cairo"];
var citynames = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: '/tags.json',
filter: function (res) {
// modify returned data here ,
// e.g., `res` : `["abc"]`
return $.map(res[0].split(""), function (val, i) {
return {
name: val.toUpperCase() === list[i][0] ? list[i] : null
};
});
}
}
});
citynames.initialize();
$('input.bootstrap-tagsinput').tagsinput({
typeaheadjs: {
name: 'citynames',
displayKey: 'name',
valueKey: 'name',
source: citynames.ttAdapter()
}
});
jsfiddle http://jsfiddle.net/guest271314/dbfx1tso/
See Bootstrap Tags Input Typeahead

Related

How to display remote results with Twitter Typeahead?

I want to use Twitter Typeahead with a remote db datasource. I managed to get the results returned from my .php file with
return json_encode($results);
The are formatted like this:
["chrome","test01","test02","wddwde"].
But I do not know how to get them to show as suggestions?
For comparison I added the prefetched 'countries_bloodhound' as well as the integration part of this variable and it works fine. I need help with 'users_bloodhound' and its integration.
var users_bloodhound = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
//name: 'users',
remote: {url:'./search.php?query=%QUERY',
wildcard: 'QUERY',
transform: function(response) {
// Map the remote source JSON array to a JavaScript object array
return $.map(response.results, function(user) {
return {
name: user
};
}
);}
},
limit: 10
});
var countries_bloodhound = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: 'https://cdn.rawgit.com/twitter/typeahead.js/gh-pages/data/countries.json',
filter: function (countries) {
return $.map(countries, function (country) {
return {
name: country
};
});
}
}
});
countries.initialize();
users_bloodhound.initialize();
$('#bloodhound .typeahead').typeahead({
highlight: true
}, {
name: 'users',
displayKey: 'name',
source: users_bloodhound.ttAdapter(),
templates: {
header: '<h4 class="search-name"><small>Users</small></h4>'
}},{
name: 'countries',
displayKey: 'name',
source: countries_bloodhound.ttAdapter(),
templates: {
header: '<h4 class="search-name"><small>Countries</small></h4>'
}
});
The code is correct. I had some problems with my .php file because I returned the results instead of echoing them.

Can't set ttl duration in bloodhound

i'm using bootstrap typeahead v0.11.1 but i'm wondering if i can set an other value for ttl (the default one is 1 day )
this is my code :
var taxes = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.name);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url :'/taxes.json'
ttl : 5000
},
remote: {
url: '/source.php?query=%QUERY',
filter: function (taxes) {
// Map the remote source JSON array to a JavaScript object array
return $.map(taxes, function (movie) {
return {
val: movie.val,
name: movie.name,
type: movie.type
};
});
},
wildcard : '%QUERY'
}
});
taxes.initialize();
$('#pretva_name').typeahead({ highlight:false,
hint: false,
offset: false,
minLength:2}, {
display: 'name',
source: taxes.ttAdapter(),
});
The remote option is working just fine but the prefetched source is always the same

how to use json on twitter typeahead

I have a json like this:
{"num": ["test", "test group event"]}
I want to use typeahead.js,
but their json is like this:
["Andorra","United Arab Emirates"]
How can I use my json for the example below?
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
var countries = new Bloodhound({
datumTokenizer : Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer : Bloodhound.tokenizers.whitespace,
limit : 10,
prefetch : {
url : 'http://127.0.0.1:8000/mysearch/',
filter : function(list) {
return $.map(list, function(country){
return {
name : country
};
});
}
}
});
countries.initialize();
$('#prefetch .typeahead').typeahead(null, {
name : 'countries',
displayKey : 'name',
source : countries.ttAdapter()
});
});//]]>
</script>
Update:
My json is coming from the server(http://rroyales.webfactional.com/mysearch/1.json) so if possible I think we have to use prefetch to get json from the server. I don't want to use getjson to capture it in a variable or is there an easier way to capture it in a variable?
Update 2:
what is wrong with my json coming from haystack - created a new question related to this
Update
This is how your bloodhound should look like
var dataSource = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('item'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: {
url: "http://jsbin.com/nixalofara/1.json",
filter: function (data) {
return $.map(data['num'], function (item) {
return {
item: item
};
});
}
}
});
And typeahead like this
$('.typeahead').typeahead({
highlight: true
}, {
displayKey: 'item',
source: dataSource.ttAdapter()
});
Here is a demo
`var data = {"num": ["one", "two"]};`
This is how your bloodhound should look like for data like above
var bloodhound = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: $.map(data['num'], function(item) { return { value: item }; })
});
And typeahead like this
$('.typeahead').typeahead({
highlight: true
}, {
source: bloodhound.ttAdapter()
});
Hope this helps.
Since your array is a property within the larger json object, I'm pretty sure you could do something like this:
var myJson = {"num": ["one", "two"]}; //capture your json object in a variable
var myArray = myJson.num; //myArray will now equal ["one", "two"]
And then, near the bottom of the code you list, you'd need to update the typeahead call accordingly.

Typeahead.js Suggest Not Rendering Properly

I am using the Typeahead.js plugin. I am trying to create custom templates for the suggestions. Currently, I have the following:
var suggestions = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: '/api/suggests?querytext=%QUERY'
});
suggestions.initialize();
$(document).ready(function() {
$('input.typeahead').typeahead(
{ minLength: 3 },
{
name: 'suggestions',
source: suggestions.ttAdapter(),
templates: {
suggestion: function(data) {
var str = '';
str += '<div>Result: ';
// if suggestion is a Customer show 1 icon and the Name
// elseif suggestion is a Product show a different icon and the name
str += '</div>';
return str;
}
}
}
);
});
The suggestions are popping up. However, I am unable to actually get the property values from inside of my results. When Bloodhound requests the suggestions, I get a result set back that looks like this:
{
"Results":[
{
"Type":"Customer",
"Id":5,
"Name":"Bill",
"LastUpdated":"01-01-2015"
},
{
"Type":"Customer",
"Id":135,
"Name":"Billows",
"LastUpdated":"01-02-2015",
},
{
"Type":"Product",
"Id":241,
"Name":"Bill Check",
"LastUpdate":"01-04-2015"
}
],
"TotalResults":3,
"TotalCustomers":2,
"TotalProducts":1
}
How do I get the individual Name and Type values for a single suggestion in the template so I can render it properly?
Thank you!
Try this
var suggestions = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/api/suggests?querytext=%QUERY',
filter: function(list) {
var suggestions = list.Results;
return $.map(suggestions, function(suggestion) { return { Type: suggestion.Type, Id: suggestion.Id, Name: suggestion.Name, LastUpdated: suggestion.LastUpdated }; });
}
}
});
suggestions.initialize();
$(document).ready(function () {
$('input.typeahead').typeahead(
{ minLength: 3 },
{
name: 'suggestions',
source: suggestions.ttAdapter(),
templates: {
suggestion: function (data) {
var str = '';
str += '<div>Result: ';
// get value by data.Type data.Name
str += '</div>';
return str;
}
}
}
);
});

Autocomplete prediction with typehead.js does not work

So I want to use typehead.js to have an autocomplete field (http://twitter.github.io/typeahead.js/) :
$(document).ready(function() {
var result;
var result = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.Domain.domain); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
prefetch: {
url: 'data.json'
}
});
result.initialize();
$('.example-twitter-oss .typeahead').typeahead(null, {
name: 'twitter-oss',
displayKey: 'Domain.domain',
source: result.ttAdapter(),
templates: {
suggestion: Handlebars.compile([
'<p class="repo-language">Class {{Domain.class}}</p>',
'<p class="repo-name"><img src="http://www.google.com/s2/favicons?domain={{Domain.domain}}" alt=""> {{Domain.domain}}</p>',
'<p class="repo-description">{{Domain.company}}</p>'
].join(''))
}
});
});
This is my data source :
[
{
"Domain":{
"domain":"duckduckgo.com",
"company":"DuckDuckGo, Inc.",
"category":"0"
}
},
{
"Domain":{
"domain":"twitter.com",
"company":"Twitter, Inc.",
"category":"0"
}
},
{
"Domain":{
"domain":"apple.com",
"company":"Apple, Inc.",
"category":"0"
}
}
]
It seems that the dropdown menu works fine, but the input field does not have the prediction displaying (I mean it you start typing "Twi" it does not display in grey "tter" ).
Any idea on how to solve this ?
Your display key is incorrect. typeahead.js will not parse your key and know that it needs to access a nested object. Instead, in order to achieve the functionality you want, do the following:
$('.example-twitter-oss .typeahead').typeahead(null, {
// ...
displayKey: function(o) { return o.Domain.domain; }
// ...
});

Categories

Resources