3

MaterializeCSS 1.0 rc1 AutoComplete with Ajax

 3 years ago
source link: https://www.aligneddev.net/blog/2018/materializecss-beta-autocomplete-ajax/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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');
        });
    }


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK