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 () { };

        _.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

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

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

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

comments powered by Disqus

Please consider using Brave and adding me to your payment ledger. Then you won't have to see ads!

Support me and download Brave!

Use Brave