MaterializeCSS 1.0 rc1 AutoComplete with Ajax

May 17, 2018    Web Development CSS

MaterializeCSS 1.0 rc1 AutoComplete with Ajax/XHR

I’m using MaterializeCSS 1.0.0-rc.1 and having good success, but there are a few things yet that can be better.

I had to spend a good amount of time figuring out how to do Ajax/XHR with the Autocomplete , so I decided to do a quick share.

There’s a current issue , so this might be better soon (I’m writing on May 17, 2018).

debounce comes from lodash .

    var schoolNameElem = document.getElementById("SchoolName");
    var instance = M.Autocomplete.getInstance(schoolNameElem);

    // we'll handle the event and ignore MaterializeCSS's approach
    instance._handleInputKeydown = function () { };

    schoolNameElem.addEventListener('keydown',
        _.debounce(function () {
                getSchools(schoolNameElem.value).then(function (data) {
                    var dataForM = {};
                    for (var i = 0; i < data.length; i++) {
                        dataForM[data[i]] = null;
                    }

                    // some hackery needed to get the data in the object format and get it to open after completion
                    instance.updateData(dataForM);

                    // my first attempt
                    instance._renderDropdown(dataForM, schoolNameElem.value);
                    instance.dropdown.isOpen = false;
                    instance.dropdown.open();

                    // slightly improved approach (comment out the lines above)
                    // Have to unfocus and focus to get materialize autocomplete to look at new data.
                    schoolNameElem.blur();  
                    schoolNameElem.focus();
                });
        }, 500)
    );

    var getSchools = function (term) {
        showLoadingIndicator('school-name-loading-indicator');
        return $.ajax({
            url: "/Account/GetSchools",
            dataType: "json",
            data: {
                term: term,
                state: $("#StateId").val(),
                schoolTypeId: $('#SchoolTypeId').val(),
                limit: 50
            }
        }).always(function () {
            hideLoadingIndicator('school-name-loading-indicator');
        });
    }


Watch the Story for Good News
I gladly accept BTC Lightning Network tips at [email protected]

Please consider using Brave and adding me to your BAT payment ledger. Then you won't have to see ads! (when I get to $100 in Google Ads for a payout, I pledge to turn off ads)

Use Brave

Also check out my Resources Page for referrals that would help me.


Swan logo
Use Swan Bitcoin to onramp with low fees and automatic daily cost averaging and get $10 in BTC when you sign up.