JavaScript Answers

How to Only Allow Selected Valued from Suggested List with jQuery UI AutoComplete?

Spread the love

To only allow selected valued from suggested list with jQuery UI AutoComplete, we can listen to the keyup event and check if the option is a valid option in the keyup event listener.

For instance, we write:

<link rel="stylesheet" href="//">
<script src=""></script>
<script src=""></script>

<input id="ac">

to add the CSS and JavaScript files for jQuery and jQuery UI.

We also add the input element for the autocomplete.

Then we write:

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

  autoFocus: true,
  source: validOptions
}).keyup(function() {
  let isValid = false;
  for (const o of validOptions) {
    if (o.toLowerCase().match(this.value.toLowerCase())) {
      isValid = true;
  if (!isValid) {
    this.value = previousValue
  } else {
    previousValue = this.value;

We call autocomplete to turn the input into an autocomplete input.

Then we call keyup to listen to the keyup event.

In the event handler, we check is the this.value input value matches the o value in the validOptions list.

If it does, then we set isValid to true.

If isValid is false, then we set the input value to previousValue to restore the input value to the old value.

Otherwise, we set previousValue to this.value to store the valid input value.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.