dzajdol
dzajdol

Reputation: 169

Autocomplete with force of a choice

I want to use autocomplete (jquery or .net) with force a choice so that the user must always choose something. There can be no possibility of entry, the user can only choose.

Does anyone know how to do this??

I want to use webservice for this purpose, because the results will be a lot, and I'll show you the first few.

I want to display text in hidden field after choosing to save the value


I want to use webservice for this purpose, because the results will be a lot, and I'll show you the first few

Upvotes: 2

Views: 2149

Answers (2)

Ben W
Ben W

Reputation: 2479

You can use jQuery autocomplete widget as it supports force selection.

        var availableTags = [
            "ActionScript",
            "AppleScript"
        ];
        $("#tags").autocomplete({
            source: availableTags,
            change: function (event, ui) {
                if(!ui.item){
                    //http://api.jqueryui.com/autocomplete/#event-change -
                    // The item selected from the menu, if any. Otherwise the property is null
                    //so clear the item for force selection
                    $("#tags").val("");
                }

            }

        });

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532565

Doing this with the jQuery UI widget is going to require a bit of extra work on your part. I suggest that you consider using the non-UI autocomplete plugin with the mustMatch option. Note, though, that if the user has javascript turned off, this will not guarantee that the value of the input is always from your set of options.

EDIT: Sample parser for the autocomplete plugin. Expects an array of JSON objects of the form:

[ {
    "FirstName" : "john",
    "LastName" : "smith",
    "Email" : "[email protected]"
  },
  ...
]

Autocomplete setup

$('.selector').autocomplete({
      ...
      parse: function(data) {
                var array = new Array();
                for(var i=0;i<data.length;i++)
                {
                    var datum = data[i];
                    var name = datum.FirstName + ' ' + datum.LastName;
                    var display =  name + ' (' + datum.Email + ')';
                    array[array.length] = { data: datum, value: display, result: name };
                }
                return array;
             },
      ...
})

Upvotes: 0

Related Questions