Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeahead.js : How to remove value when value not in suggestion

I use typeahead.js as autocomplete textbox.

At first, when I input and select a value from the suggestions, textbox sets the value correctly. Then, I input a value that is not in the suggestions and press tab and the value of the textbox doesn't clear.

How do I clear the value of the textbox when the input value is not in the suggestions.

like image 828
Tuan Hoang Anh Avatar asked Dec 30 '25 16:12

Tuan Hoang Anh


2 Answers

I ran into the same situation and the way I solved this was by using the events of typeahead.js. I record a selection on typeahead:select and then check on typeahead:change if the selection was made. If no selection was made, I reset the input to the original value.

// Initialize typeahead as ususal
var $myTypeahead = $("#my-typeahead");
$myTypeahead.typeahead(/* Set-up typeahead here */);

// Set up variables to store the selection and the original 
// value.
var selected      = null;
var originalVal   = null;

// When the typeahead becomes active reset these values.
$myTypeahead.on("typeahead:active", function(aEvent) {
   selected       = null;
   originalVal    = $myTypeahead.typeahead("val");
})

// When a suggestion gets selected save that
$myTypeahead.on("typeahead:select", function(aEvent, aSuggestion) {
   selected = aSuggestion;
});

// Once user leaves the component and a change was registered
// check whether or not something was selected. If not reset to
// the original value.
$myTypeahead.on("typeahead:change", function(aEvent, aSuggestion) {
   if (!selected) {
      $myTypeahead.typeahead("val", originalVal);
   }

   // Do something with the selected value here as needed...
});   
like image 59
ced-b Avatar answered Jan 01 '26 04:01

ced-b


If you are using typeahead.js with Bootstrap Tags Input, which I highly recommend due to it's power, there is an option called freeInput that you can turn false to not allow tags that are not returned by typeahead's source.

Here's an example of how you can use it:

$('input').tagsinput({
  typeahead: {
    source: ['Amsterdam', 'Washington', 'Sydney', 'Beijing', 'Cairo']
  },
  freeInput: false
});

That way, your tags will be limited to what the source returns, like Amsterdam, Washington, Sydney ...

like image 41
Ricarte Avatar answered Jan 01 '26 04:01

Ricarte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!