How to implement “mustMatch” and “selectFirst” in jQuery UI Autocomplete?

前端 未结 13 869
一向
一向 2020-11-27 11:47

I recently migrated a few of my Autocomplete plugins from the one produced by bassistance to the jQuery UI autocomplete.

How can the \"mustMatch\" and \"selectFirst\

相关标签:
13条回答
  • 2020-11-27 12:46

    Maybe it's just because this is an old issue, but I found that the easiest solution is already there in the plugin, you just need to use the proper functions to access it.

    This code will handle the cases when the autocomplete loses focus with an invalid value:

    change: function(e, ui) {
        if (!ui.item) {
            $(this).val("");
        }
    }
    

    And this code, much like the original functionality from bassistance, will handle the cases when there are no matches while typing in the autocomplete:

    response: function(e, ui) {
        if (ui.content.length == 0) {
            $(this).val("");
        }
    }
    

    This works well with either a static array source, or a JSON data source. Combined with the autoFocus: true option, it seems to do everything needed in an efficient manner.

    The last case that you may want to handle is what to do when the ESCAPE key is pressed with an invalid value in the textbox. What I do is use the value of the first matched result. And this is how I do that...

    First, declare a variable to hold the best match. Do this outside of your autocomplete plugin.

    var bestMatch = "";
    

    Then use the following option:

    open: function(e, ui) {
        bestMatch = "";
    
        var acData = $(this).data('uiAutocomplete');
        acData.menu.element.find("A").each(function () {
            var me = $(this);
    
            if (me.parent().index() == 0) {
                bestMatch = me.text();
            }
        });
    }
    

    Lastly, add the following event to your autocomplete:

    .on("keydown", function(e) {
        if (e.keyCode == 27)        // ESCAPE key
        {
            $(this).val(bestMatch);
        }
    })
    

    You can just as easily force the field to be empty when the escape key is pressed. All you have to do is set the value to an empty string when the key is pressed instead of the bestMatch variable (which isn't needed at all if you choose to empty the field).

    0 讨论(0)
提交回复
热议问题