Force Autocomplete Widget Selection if an exact match is available, but allow non-matching entries

StackOverflow https://stackoverflow.com/questions/23374730

  •  12-07-2023
  •  | 
  •  

Question

My old title was "Something similar to mustMatch for JQ UI Autocomplete" But I don't know if it was explanatory enough.

I'm not sure if showing my code will make any difference for this question, so I am leaving it out for now.

I have JQuery UI Autocomplte widget working. I found an edge case that I'm not sure how to handle. Let's say the searchable values includes "The Rage" and a new item is entered called "The Rag".

Well, the [ESC] key lets you exit autocomplete without making a selection. This is desireable in my case.

What is NOT desireable is that if, in this case, someone types "The Rage" and hits [ESC] then "The Rage" is in the input field, but my script does not know it is an existing item, so I need "must match if exact match available"

I am initializing it like this:

$( "#company-name" ).autocomplete();
$( "#company-name" ).autocomplete({ source: "autocomplete/company_ac.php"});
$( "#company-name" ).autocomplete( "option", "minLength", 3 );
$( "#company-name" ).autocomplete({ autoFocus: true });
$( "#company-name" ).autocomplete( "enable" );
Was it helpful?

Solution

Here's how I did it:

I was already setting ac_selected to false on open:

  $( "#company-name" ).autocomplete({
    open: function(event, ui) {
      $( "#company-name" ).data( {ac_selected: false} );
    }
  });

Then I set another data "found" on autocompleteresponse

  $( "#company-name" ).on( "autocompleteresponse", function( event, ui ) {
    $( "#company-name" ).data({found: JSON.stringify(ui)} );
  } );

and then checked for a match on close

  $( "#company-name" ).autocomplete({
    close: function(event, ui) {
      if ($( "#company-name" ).data("ac_selected")===false) {
        var needle = $( "#company-name" ).val();
        var haystack = JSON.parse( $( "#company-name" ).data("found") );
        // The array I need to filter is actually contained in the content property
        var result = haystack.content.filter(function ( input ) {
          return input.label.toLowerCase() === needle.toLowerCase(); // do a case insensitive search
        })[0];
        if(result){
          $( "#company-name" ).data( {ac_selected: true} );
          $( "#company-name" ).val(result.label);
        }
      }
    }
  });  
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top