Search code examples
javascriptjqueryjquery-ui-autocompleteeasyautocomplete

How can I limit users to only pick from options listed in EasyAutoComplete (jquery)?


I'm using EasyAutoComplete (http://easyautocomplete.com/), which while it does utilize jquery, is different from the standard jquery ui autocomplete. I'm trying to make it so that users can only select an item that is from the list that gets generated. I found the answer I wanted for the standard jquery ui autocomplete here: jQuery UI autocomplete: enforce selection from list without modifications

The issue is that I'm not quite sure how I can take that code and implement it along with EasyAutoComplete. Specifically, I would like to use this bit:

    change: function (event, ui) {
        if (ui.item == null || ui.item == undefined) {
            $("#artist").val("");
            $("#artist").attr("disabled", false);
        } else {
            $("#artist").attr("disabled", true);
        }
    }

While the documentation for EasyAutoComplete does provide several event handlers, none of them are for the event that I want. I'm guessing I would need to somehow work this into the jquery.easy-autocomplete.min.js code itself, but I am at a loss at where to even start with that!

What is the best way to approach this?


Solution

  • It took a bit of research, but I actually was able to come up with a solution. Rather than using change() inside the options for autocomplete, you can use it outside. Plus, the API has a getSelectedItemData() function you can use to pull the item data.

    $("#artist").change(function () {
        let selectedvalue = $("#artist").getSelectedItemData();
        let specval = selectedvalue[0];
        
        if (specval == "undefined" || specval == null) {
            $("artist").val("");
        }
    });
    

    It's worth noting, while EasyAutoComplete does have events for OnClick and OnKeyEnter, there isn't a nice and easy catch-all available. You would have to program out these events separately, which is not DRY coding. Plus they don't have an event for when the user clicks off the screen, outside of the select box.