meer
meer

Reputation: 225

text field jquery auto-complete - only allow submissions within autocomplete options

I am looking for help in my code that allows an autocomplete, only within a specified data array. So only data within the auto complete array is allowed to be entered. Not sure where to do that .Here is my code. Can anyone suggest ??

 $(document).ready(function () {
                         var data = ["ActionScript","AppleScript","Asp","BASIC","C","C++","iran","Scheme"];
                        $("#autocomplete").autocomplete(data);
                        });
    $('input#autocomplete').result(function (event, data, formatted) {
                        $("#result").html(!data ? "No match found!" : "Selected: " + formatted);
                    }).keyup(function () {
                       $(this).search();
                       $(this).css("background-color","#D6D6FF");                   
                    });

             } catch (e) { }
        });

Upvotes: 1

Views: 2521

Answers (3)

Doug Conran
Doug Conran

Reputation: 459

I do the following:-

  1. Set a flag to false when entering the field (onfocus)
  2. Set the flag to true in the autocomplete select event
  3. Test the flag in the field onblur event

If it is true the selection is good other wise it is bad and you can return focus to the input field.

Upvotes: 0

larshaeuser
larshaeuser

Reputation: 388

You can simply disable the input field after the user selected a specific value. see line 6 in example code

example:

$("#autocomplete2").autocomplete({
  url:'search.php?type=xml',
  minchar:2,
  delay:1000, // in milliseconds
  onSelect:function(){
    $("#autocomplete2").attr('disabled', 'disabled');
  },
  type:'xml'
});

Upvotes: 0

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

Try the mustMatch option (docs):

$("#autocomplete").autocomplete(data, { mustMatch: true });

Example: http://jsfiddle.net/prCsm/

As a side note, this plugin has been deprecated in favor of the jQueryUI version.

Upvotes: 2

Related Questions