I am new to the use of the typeahead plugin and my javascript(not jquery) skills are terrible. This is my JSON:
{"Product":[
{"@ProductCode":"C1010","@CategoryName":"Clips"},
{"@ProductCode":"C1012","@CategoryName":"Clips"},
{"@ProductCode":"C1013","@CategoryName":"Clips"},
{"@ProductCode":"C1014","@CategoryName":"Clips"},
{"@ProductCode":"C1015","@CategoryName":"Clips", "EAN":"0987654321"}
]}
I have the typeahead bundle 0.10.5 And this is my js:
$(document).ready(function () {
var products = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 100,
remote: {
url: 'TypeAhead.ashx?q=%QUERY&cat=prod',
filter: function (data) {
return data.Products;
}
}
});
products.initialize();
$("#tbSSearch").typeahead({
highlight: true,
minLength: 2
}, {
source: products.ttAdapter(),
displayKey: function (products) {
return products.product.code;
},
templates: {
header:"<h3>Products</h3>"
}
});
});
Chrome console gives me:
Uncaught TypeError: Cannot read property 'length' of undefined
But that is in my jquery.2.1 (minified) lib and not the above js source. browser shows no popup below #tbSearch
input.
as @Mike suggested, jsfiddle http://jsfiddle.net/gw0sfptd/1/ but I had to modify some stuff to work with local json. and this also does not work LOL
edit as David suggested, I should clean up my json. so it is now :
[{"Code":"C1010","Gtin13":0,"CategoryName":"Clips"},
{"Code":"C1012","Gtin13":0,"CategoryName":"Clips"},
{"Code":"C1013","Gtin13":0,"CategoryName":"Clips"}]
and the js:
remote: {
url: 'TypeAhead.ashx?q=%QUERY&cat=prod',
filter: function (products) {
return $.map(products.results, function (product) {
return {
value: product.Code
};
});
}
}
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
But no working typeahead and no (useable)error in firefox console. My desired output would be a list of productcode, but also the category that they are in and the gtin13 (if not null) because the sql searches for all those three options. Should I make a javascript 'class' for product on the client side and parse the json to it? It is still unclear to me how the whole bloodhound thing works. (yes I have looked at the samples and read the docs of both typeahead and bloodhound) I don't know if it is possible but what my ultimate wish is, is that when you select an item from the typeahead suggestions this productdatasource links to productdetail.aspx and if you select an item of the categorydatasource (not visisble in this question) that it redirects the page to categorydetail.aspx