Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Autocomplete - Force choice

I have a form working with JQuery Autocomplete and it works fairly well. Now I need another element to force a user to select a valid choice in the autocomplete input. The can type whatever they want and everything is filtered by autocomplete. But they have to select something from the served list. If they don't the inputfield must get blanked. Tried out a few things with change and select to no avail. This is the code of my autocomplete. I saw some examples operation with data instead of source. This seems to make a big difference

$(function () {
    $("#sp_name").autocomplete({
        minLength: 2,
        delay: 300,
        source: function (request, response) {
            $.ajax({
                url: "./Search/",
                dataType: "json",
                data: {
                    term: request.term,
                    zoekterm: $("#al").html()
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.naam,
                            value: item.naam
                        }
                    }));
                }
            });
        }
    })
});
like image 840
Pattux Avatar asked Sep 10 '13 13:09

Pattux


People also ask

How do I force a user to select from AutoComplete?

For the selection action, try using the formatItem option. You can format each result to have an onclick event that will populate the other textbox. For the forcing to select from autocomplete, you need to use the mustMatch option.

What is the function of AutoComplete?

AutoComplete helps you quickly insert functions and arguments while minimizing typing and syntax errors. The AutoComplete menu shows you available options based on context, and you choose what you want to insert into your formula.


1 Answers

Try this:

I am using a local list here, but you can achieve this via json data source too. Just add a change event. The only problem this can have is that if user does not click on the suggestion, it will turn blank (even if user is entering the same text as suggestion). It will be mandatory for user to click on the suggestion.

var list = ["c", "c++", "c#","Basic","Mongo"];

$('#auto').autocomplete({
source: list,

select: function (event, ui) {
    $(this).val(ui.item ? ui.item : " ");},

change: function (event, ui) {
    if (!ui.item) {
        this.value = '';}
//else { Return your label here }
}
}); 

JsFidle for it: http://jsfiddle.net/sarcastic/7KdZP/112/

In your case, Change function would be something like this:

change: function (event, ui)
{
if (!ui.label) { this.value = ''; }
}
like image 199
Sarcastic Avatar answered Sep 22 '22 23:09

Sarcastic