Search code examples
ajaxmaterialize

Materialize autocomplete : Why AJAX called before entering any character?


I'm using autocomplete with materialize and i'm retrieving the data with ajax call, it works fine but when i want to call ajax only after entering caracters(using onkeyup event), the drop down list will not be showing correctly !!!! Before i forget please help me to show a "NOT FOUND" in the drop down list if no data founded (because my else condition doesn't work). here is my code and thanks a lot in advance :

$(document).ready(function() {
    var contents = $('#autocomplete-input')[0];
    contents.onkeyup = function (e) {

    $.ajax({
        type: 'GET',
        url: Routing.generate('crm_search_lead', {"search": 
        $(this).val()}),
        success: function (response) {
            var contacts = {};
            if (true === response.success) {
                var result = response.result;
                for (var i = 0; i < result.length; i++) {
                    var lastName = result[i].lastName ? 
                    result[i].lastName : '';
                    var firstName = result[i].firstName ? 
                    result[i].firstName : '';

                    contacts[lastName + " " + firstName] = null;
                }
                $('input.autocomplete').autocomplete({
                    data: contacts,
                    minLength: 2,

                });

            } else {
                $('input.autocomplete').autocomplete({
                    data: {
                        "NOT FOUND": null
                    }

                });
            }
        }
    });
    }
});

Solution

  • Hi people :) i resolve it by changing onkeyup() with focus() and it's totally logical because with onkeyup() the droplist will appear and disappear very quickly on every key entered.