Jquery autocomplete - only allow autocomplete suggestions

310 Views Asked by At

I use this jQuery Autocomplete - framework for an input field (after input of three characters the suggestions appear), and I only will allow entries of autocomplete suggestion.

My first approach was:

var nameSelectedOverSearch = false;
var availablePersons = [];
$(function() {
    $("#anspr").autocomplete({
        source: availablePersons,
        select: function(event, ui) {
            nameSelectedOverSearch = true;
        }
    });
});

the user must click an autocomplete suggestion but it is still possible that afterwards the user change the input. Is there any possibility to only allow autocomplete inputs?

2

There are 2 best solutions below

2
Quentin Roger On BEST ANSWER

You can use this awesome library https://harvesthq.github.io/chosen/. I did a full exemple with autocomplete and chosen to compare : https://jsfiddle.net/Tintin37/uw52snsq/

I think it fits exactly your needs.

Relevant code :

    $("#tags").autocomplete({
      source: availableTags
    });

    $.each(availableTags,function(i,e){
             $("#choosen").append('<option>'+e+'</option>');   
    });
    $("#choosen").chosen({search_contains: true});
0
Yaina Villafañes On

You need to use the function "keyup" in this way you can validate any letter and only allow the options on you list:

$('#tags').autocomplete({
  autoFocus: true,
  source: availableTags 
  }).keyup(function() {
    var isValid = false;
    for (i in availableTags) {
        if (availableTags[i].toLowerCase().match(this.value.toLowerCase())) {
            isValid = true;
        }
    }
    if (!isValid) {
        this.value = previousValue
    } else {
        previousValue = this.value;
    }
});