Amir
Amir

Reputation: 4760

jQuery Autocomplete: How to disallow free text, and display an error that an item from the list must be selected?

I know javascript just enough to be dangerous and I’ve been reading through the documentation for the autocomplete widget but could not find anything on the subject.

An old version of the widget did have an option called: mustMatch but I don’t see anything with the new version.

I figured out at least how to force at least two characters to be typed in before autompletion starts. I did that by adding this line: $( "#user-city" ).autocomplete({ minLength: 2}); I have a feeling this can be folded into the code below it, but I don’t know how.

Anyway, is there a way to force the automplete to only accept values from the list? And then maybe show a div “You must select a value from the list” if they continue to type in some free text? Then if they just deselect the box, it removes whatever they have typed in, since it did not match anything.

$(function() {
        var names = [ "Boston", "New York", "New Jersey", "Kansas City", "Los Angeles" ];

        var accentMap = {
            "á": "a",
            "ö": "o"
        };
        var normalize = function( term ) {
            var ret = "";
            for ( var i = 0; i < term.length; i++ ) {
                ret += accentMap[ term.charAt(i) ] || term.charAt(i);
            }
            return ret;
        };

        $( "#user-city" ).autocomplete({ minLength: 2});

        $( "#user-city" ).autocomplete({
            source: function( request, response ) {
                var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
                response( $.grep( names, function( value ) {
                    value = value.label || value.value || value;
                    return matcher.test( value ) || matcher.test( normalize( value ) );
                }) );
            }
        });
    });

Here is the jsfiddle: http://jsfiddle.net/HKzL7/

Thanks for the help!

Upvotes: 0

Views: 1898

Answers (1)

The Alpha
The Alpha

Reputation: 146191

I think you can use change event and can check if the ui.item is null then you can make the input empty and show an alert or custom message, for example (just an idea)

change: function( event, ui ) {
    if(ui.item==null) 
    {
        this.value='';
        alert('Please select a value from the list'); // or a custom message
    }
}

DEMO.

Update: change event fires when the field is blurred, if the value has changed.

Upvotes: 3

Related Questions