DEV Community

Cover image for How to make a html search datalist for Vue
Brett Anda πŸ”₯🧠 for Developer Bacon πŸ₯“πŸ₯“

Posted on • Originally published at developerbacon.ca on

How to make a html search datalist for Vue

What do I mean by search suggestions

An example where I have use a datalist is on the search page. Another axample of this in action would look like this:

See the Pen HTML Search with datalists by Brett
(@brettanda) on CodePen.

Adding the datalist to an input

To add a datalist to a text input you will need to add list="id" to your text input. For this, to work the list attribute needs to be set to the id of the datalist element.

<input type="search" placeholder="Search" list="data" />

Enter fullscreen mode Exit fullscreen mode

Creating the datalist element

The datalist element is like the select element.

<datalist id="data">
    <option value="HTML" />
    <option value="CSS" />
    <option value="JavaScript" />
</datalist>

Enter fullscreen mode Exit fullscreen mode

Implementing Vue

let us say you have a search form component using the above datalist and search input.

<form>
    <input type="search" placeholder="Search" list="data" />

    <datalist id="data">
        <option value="HTML" />
        <option value="CSS" />
        <option value="JavaScript" />
    </datalist>
</form>

Enter fullscreen mode Exit fullscreen mode

Let's say that you have an array of search values that you would like to display in this datalist, for example, this array:

export default {
    data() {
        return {
            list: ["HTML", "CSS", "JavaScript"]
        };
    }
};
Enter fullscreen mode Exit fullscreen mode
<form>
    <input type="search" placeholder="Search" list="data" />

    <datalist id="data">
        <option v-for="item in list" :key="item" :value="item" />
    </datalist>
</form>

Enter fullscreen mode Exit fullscreen mode

Adding Gridsome

So you are using Gridsome (like me). Let's say that you would like your posts titles to show in this data list, You will need a page-query and use that instead of the data array.

<page-query>
query Search {
  allPost {
    edges {
      node {
        title
      }
    }
  }
}
</page-query>

Enter fullscreen mode Exit fullscreen mode

Now for the new datalist.

<form>
    <input type="search" placeholder="Search" list="data" />

    <datalist id="data">
        <option v-for="{ item } in $page.allPost.edges" :key="node.title" :value="node.title" />
    </datalist>
</form>

Enter fullscreen mode Exit fullscreen mode

Top comments (0)