Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeahead calling functions .val .open .close etc throws errors

I am struggling to call typeahead.js functions like val, open, close, etc.

The typeahead works properly on the input element as it displays the entries but when I try to call any typeahead function I get this error:

Uncaught Error: one of local, prefetch, or remote is requiredmessage: "one of local, prefetch, or remote is required

My init code is as follows:

var currentMedicalAid;

var medicalAidList = $('#medicalAidList');


var medicalAidengine = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('MedicalAid1'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 5,
    prefetch: {
        url: '/api/Search/GetMedicalAidList',
    }
});


medicalAidengine.initialize();


medicalAidList.typeahead(null, {
    name: 'MedicalAid1',
    displayKey: 'MedicalAid1',
    // `ttAdapter` wraps the suggestion engine in an adapter that
    // is compatible with the typeahead jQuery plugin
    source: medicalAidengine.ttAdapter()
}).blur(function () {
    match = false;
    for (var i = medicalAidengine.index.datums.length - 1; i >= 0; i--) {
        if ($(this).val() == medicalAidengine.index.datums[i].MedicalAid1) {
            currentMedicalAid = medicalAidengine.index.datums[i].MedicalAidID;
            match = true;
        }
    };
    if (!match) {
        currentMedicalAid = '00000000-0000-0000-0000-000000000000';
        $(this).val('');
        medicalAidList.typeahead('val', ''); // throws error
    }
});;

Everytime I run either one of these functions, I get an error:

medicalAidList.typeahead('val', '');
or
$('#medicalAidList').typeahead('val','');

Any help would be greatly appreciated

Thanks

like image 819
Piotr Stulinski Avatar asked Nov 10 '22 00:11

Piotr Stulinski


1 Answers

The initialize method is asynchronous. It is possible that some of your code are running when the Bloodhound engine is not fully initialized. You might need to wrap the rest of your code in a callback:

// initialize returns a jQuery promise, so we can call its done method
medicalAidengine.initialize().done(function(){

// Rest of your code

})
like image 116
parchment Avatar answered Nov 15 '22 11:11

parchment