jQuery UI AutoComplete: Only allow selected valued from suggested list

71,486

Solution 1

I got the same problem with selected not being defined. Got a work-around for it and added the toLowerCase function, just to be safe.

$('#' + specificInput).autocomplete({ 
  create: function () {
    $(this).data('ui-autocomplete')._renderItem = function (ul, item) {
      $(ul).addClass('for_' + specificInput); //usefull for multiple autocomplete fields
      return $('<li data-id = "' + item.id + '">' + item.value + '</li>').appendTo(ul); 
    };
  }, 
  change:
    function( event, ui ){
      var selfInput = $(this); //stores the input field
      if ( !ui.item ) { 
        var writtenItem = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val().toLowerCase()) + "$", "i"), valid = false;

        $('ul.for_' + specificInput).children("li").each(function() {
          if($(this).text().toLowerCase().match(writtenItem)) {
            this.selected = valid = true;
            selfInput.val($(this).text()); // shows the item's name from the autocomplete
            selfInput.next('span').text('(Existing)');
            selfInput.data('id', $(this).data('id'));
            return false;
          }
        });

        if (!valid) { 
          selfInput.next('span').text('(New)');
          selfInput.data('id', -1); 
        }
    }
}

Solution 2

You could also use this:

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

The only drawback I've seen to this is that even if the user enters the full value of an acceptable item, when they move focus from the textfield it will delete the value and they'll have to do it again. The only way they'd be able to enter a value is by selecting it from the list.

Don't know if that matters to you or not.

Solution 3

http://jsfiddle.net/pxfunc/j3AN7/

var validOptions = ["Bold", "Normal", "Default", "100", "200"]
previousValue = "";

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

Solution 4

i just modify to code in my case & it's working

selectFirst: true,
change: function (event, ui) {
        if (ui.item == null){ 
         //here is null if entered value is not match in suggestion list
            $(this).val((ui.item ? ui.item.id : ""));
        }
    }

you can try

Solution 5

This is how I did it with a list of settlements:

 $("#settlement").autocomplete({
  source:settlements,
  change: function( event, ui ) {
  val = $(this).val();
  exists = $.inArray(val,settlements);
  if (exists<0) {
    $(this).val("");
    return false;
  }
 }
});
Share:
71,486

Related videos on Youtube

stephen776
Author by

stephen776

Self-motivated software engineer with nearly a decade of experience implementing software solutions working for multiple startups and government. Comfortable working in demanding, fast-paced environments and contributing to strategies to bring products to market. Have helped to launch multiple products with startups in the Pittsburgh area, working with cross- functional teams to design and implement software solutions in support of core business models.

Updated on October 02, 2020

Comments

  • stephen776
    stephen776 over 3 years

    I am implementing jQuery UI Autocomplete and am wondering if there is any way to only allow a selection from the suggested results that are returned as opposed to allowing any value to be input into the text box.

    I am using this for a tagging system much like the one used on this site, so I only want to allow users to select tags from a pre-populated list returned to the autocomplete plugin.

  • collimarco
    collimarco over 11 years
    When you don't use ids but only labels you may want to use this instead: (inside change function) if (!ui.item) { $(this).val(''); }
  • asologor
    asologor over 9 years
    When you select an item via pressing "Enter" key - ui will be always null. jQuery UI v1.11.0
  • Jeff Lowery
    Jeff Lowery over 9 years
    I don't know why the linked-to example makes things so complicated. This version doesn't require an extra control and is pretty easy to understand: jsfiddle.net/jlowery2663/o4n29wn3
  • B2K
    B2K over 8 years
    This is not working for me. select is undefined, and I suspect that input is as well. Do you have a version of this that has actually been tested?
  • BornToCode
    BornToCode over 8 years
    This solution worked for me without the side effect you mentioned (of value being deleted when moving focus from the text field). Checked with jQuery autocomplete v1.8.
  • webzy
    webzy about 8 years
    Trying this but all values showing null. Cannot select anything
  • TarangP
    TarangP over 6 years
    is it valid usage for form when in form their have lots of jquery functions ?
  • Anup Sharma
    Anup Sharma about 6 years
    This doesn't work if you enter substring of any of the allowed items.
  • muka.gergely
    muka.gergely over 4 years
    This code sample might be answering a question, but it's not clear that it does. Please elaborate your answer so it's easier to understand what it does and why.
  • nircraft
    nircraft over 4 years
    While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
  • ArabianMaiden
    ArabianMaiden about 3 years
    @collimarco both the answer and your comment worked like a charm. I really work much better with the tab and enter keys.