I am using typeahead.js.
When I get the data from the apiController it looks like this:
["JobName1", "JobName1", "akhsfkh"]
When It gets passed through this code:
$(function() {
var projectNumbers = $.getJSON("api/Project/GetAllNumbers")
.done(function(result) {
console.log(result);
return result; // ["JobName1", "JobName1", "akhsfkh"] is here
})
.fail(function(jqXHR, textStatus, err) {
alert('Error: ' + err);
});
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substrRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
// the typeahead jQuery plugin expects suggestions to a
// JavaScript object, refer to typeahead docs for more info
matches.push({ value: str });
}
});
cb(matches);
};
};
$('#jobNumber').typeahead({
hint: true,
minLength: 2,
highlight: true,
},
{
name: 'projects',
source: substringMatcher(projectNumbers.serializeArray()),
});
});
my input box shows the type ahead but the available data is:
JobName1, JobName1, akhsfkh
The substringMatcher function didn't change it.
Any suggestions?
You cannot return results from a getJSON request like that
You have to store the result and in the callback do the rest of the stuff.
var projectNumbers;
$.getJSON("http://jsbin.com/heyobi/1.json")
.done(function (result) {
projectNumbers = result;
initTypeahead();
})
.fail(function (jqXHR, textStatus, err) {
alert('Error: ' + err);
});
var substringMatcher = function (strs) {
......
});
function initTypeahead() {
$('.typeahead').typeahead({
hint: true,
minLength: 2,
highlight: true,
}, {
name: 'projects',
source: substringMatcher(projectNumbers),
});
}
Here is a DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With