search results:

    • Standard
    • React
    Pricing Learn Community
    • + D
    • Light
    • Dark
    • System
    logo TW Elements
    • Getting started
      • Quick start
      • Tutorials
      • Design system
      • Local installation
      • Optimization
      • Dark mode
      • Theming
      • Changelog
      • Migrating to v2
      • Internationalization guide
      • Class customization
      • Icons Integration
    • CommercialNew
      • Pricing
      • License
      • Installation
      • Git & repository
      • Premium Support
    • Integrations
      • Angular
      • ASP.NET
      • Django
      • Express
      • Laravel
      • Next
      • Nuxt
      • Qwik
      • React
      • Remix
      • Solid
      • Svelte
      • SvelteKit
      • Vue
    • Content & styles
      • Animations
      • Animations Extended
      • Colors
      • Dividers
      • Figures
      • Headings
      • Hover effects
      • Icons
      • Images
      • Mask
      • Shadows
      • Typography
    • Navigation
      • Breadcrumbs
      • Footer
      • Headers
      • Mega menu
      • Navbar
      • Offcanvas
      • Pagination
      • Pills
      • Scrollspy
      • Sidenav
      • Tabs
    • Components
      • Accordion
      • Alerts
      • Avatar
      • Badges
      • Button group
      • Buttons
      • Cards
      • Carousel
      • Chips
      • Collapse
      • Dropdown
      • Gallery
      • Jumbotron
      • Lightbox
      • Link
      • List group
      • Modal
      • Notifications
      • Paragraphs
      • Placeholders
      • Popconfirm
      • Popover
      • Progress
      • Rating
      • Scroll back to top button
      • Social buttons
      • Spinners
      • Stepper
      • Testimonials
      • Timeline
      • Toast
      • Tooltip
      • Video
      • Video carousel
    • Forms
      • Autocomplete
      • Checkbox
      • Datepicker
      • Datetimepicker
      • File input
      • Form templates
      • Input Group
      • Inputs
      • Login form
      • Multi range slider
      • Radio
      • Range
      • Registration form
      • Search
      • Select
      • Switch
      • Textarea
      • Timepicker
      • Validation
    • Data
      • Charts
      • Charts advanced
      • Datatables
      • Tables
    • Methods
      • Clipboard
      • Infinite scroll
      • Lazy loading
      • Loading management
      • Ripple
      • Scrollbar
      • Smooth scroll
      • Sticky
      • Touch
    • Design Blocks
      • Admin Charts
      • Admin Complex
      • Admin Forms
      • Admin Maps
      • Admin Navigation
      • Admin tables
      • Banners
      • Contact
      • Content
      • CTA
      • FAQ
      • Features
      • Headers
      • Hero / Intro sections
      • Logo clouds
      • Mega menu
      • News
      • Newsletter
      • Pricing
      • Projects
      • Stats
      • Stats admin
      • Team
      • Testimonials
    • Tools
      • Button generator
      • Card generator
      • Flexbox generator
      • Footer generator
      • Form builder
      • Grid generator
      • Icon generator
      • Instagram Filters generator
      • Logo generator
      • Table generator
      • Typography generator
    • Coming Soon
      • Angular
      • Builder
      • Templates
      • Vue
    • Resources
      • Playground
      • YouTube Channel
      • Private FB Group
      • Newsletter
      • UI Design course New
      • UI / UX tips
    • Overview
    • API

    Autocomplete

    Tailwind CSS Autocomplete

    Autocomplete component predicts the words being typed based on the first few letters given by the user. You can search the list using basic scroll and the keyboard arrows.


    Basic example

    The filter option is required in order for component to work properly. The option accepts a function that is expected to return an array of results or a Promise that resolves to an array of results.

    • HTML
    • javascript
    • umd
            
                
          <div class="relative" data-twe-input-wrapper-init id="basic">
            <input
              type="text"
              class="peer block min-h-[auto] w-full rounded border-0 bg-transparent px-3 py-[0.32rem] leading-[1.6] outline-none transition-all duration-200 ease-linear focus:placeholder:opacity-100 peer-focus:text-primary data-[twe-input-state-active]:placeholder:opacity-100 motion-reduce:transition-none dark:text-white dark:placeholder:text-neutral-300 dark:autofill:shadow-autofill dark:peer-focus:text-primary [&:not([data-twe-input-placeholder-active])]:placeholder:opacity-0"
              id="exampleFormControlInput1" />
            <label
              for="exampleFormControlInput1"
              class="pointer-events-none absolute left-3 top-0 mb-0 max-w-[80%] origin-[0_0] truncate pt-[0.37rem] leading-[1.6] text-neutral-500 transition-all duration-200 ease-out peer-focus:-translate-y-[0.9rem] peer-focus:scale-[0.8] peer-focus:text-primary peer-data-[twe-input-focused]:-translate-y-[0.9rem] peer-data-[twe-input-state-active]:-translate-y-[0.9rem] peer-data-[twe-input-focused]:scale-[0.8] peer-data-[twe-input-state-active]:scale-[0.8] peer-data-[twe-input-focused]:text-primary motion-reduce:transition-none dark:text-neutral-400 dark:peer-focus:text-primary"
              >Example label
            </label>
          </div>
          
            
        
            
                
          import { Autocomplete, Input, initTWE } from "tw-elements";
          initTWE({ Input });
          
          const data = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight'];
    
          const dataFilter = (value) => {
            return data.filter((item) => {
              return item.toLowerCase().startsWith(value.toLowerCase());
            });
          };
    
          const basicAutocomplete = document.querySelector('#basic');
    
          new Autocomplete(basicAutocomplete, {
            filter: dataFilter,
          });
          
            
        
            
                
          const data = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight'];
    
          const dataFilter = (value) => {
            return data.filter((item) => {
              return item.toLowerCase().startsWith(value.toLowerCase());
            });
          };
    
          const basicAutocomplete = document.querySelector('#basic');
    
          new twe.Autocomplete(basicAutocomplete, {
            filter: dataFilter,
          });
    
          
            
        

    Hey there 👋 we're excited about TW elements and want to see it grow! If you enjoy it, help the project grow by sharing it with your peers. Every share counts, thank you!

    Display value

    The displayValue option allow to separate oryginal result value from the value that will be displayed in the result list or input (after selection). Its useful when the data returned by the filter function is an array of objects. You can specify which parameter of the object should be displayed.

    • HTML
    • javascript
    • umd
            
                
          <div class="relative" data-twe-input-wrapper-init id="displayValue">
            <input
              type="text"
              class="peer block min-h-[auto] w-full rounded border-0 bg-transparent px-3 py-[0.32rem] leading-[1.6] outline-none transition-all duration-200 ease-linear focus:placeholder:opacity-100 peer-focus:text-primary data-[twe-input-state-active]:placeholder:opacity-100 motion-reduce:transition-none dark:text-white dark:placeholder:text-neutral-300 dark:autofill:shadow-autofill dark:peer-focus:text-primary [&:not([data-twe-input-placeholder-active])]:placeholder:opacity-0"
              id="exampleFormControlInput2" />
            <label
              for="exampleFormControlInput2"
              class="pointer-events-none absolute left-3 top-0 mb-0 max-w-[80%] origin-[0_0] truncate pt-[0.37rem] leading-[1.6] text-neutral-500 transition-all duration-200 ease-out peer-focus:-translate-y-[0.9rem] peer-focus:scale-[0.8] peer-focus:text-primary peer-data-[twe-input-focused]:-translate-y-[0.9rem] peer-data-[twe-input-state-active]:-translate-y-[0.9rem] peer-data-[twe-input-focused]:scale-[0.8] peer-data-[twe-input-state-active]:scale-[0.8] peer-data-[twe-input-focused]:text-primary motion-reduce:transition-none dark:text-neutral-400 dark:peer-focus:text-primary"
              >Example label
            </label>
          </div>
          
            
        
            
                
          import { Autocomplete, Input, initTWE } from "tw-elements";
          initTWE({ Input });
    
          const customData = [
            { title: 'One', subtitle: 'Secondary text' },
            { title: 'Two', subtitle: 'Secondary text' },
            { title: 'Three', subtitle: 'Secondary text' },
            { title: 'Four', subtitle: 'Secondary text' },
            { title: 'Five', subtitle: 'Secondary text' },
            { title: 'Six', subtitle: 'Secondary text' },
          ];
    
          const customFilter = (value) => {
            return customData.filter((item) => {
              return item.title.toLowerCase().startsWith(value.toLowerCase());
            });
          };
    
          const displayValueAutocomplete = document.querySelector('#displayValue');
    
          new Autocomplete(displayValueAutocomplete, {
            filter: customFilter,
            displayValue: (value) => value.title,
          });
    
          
            
        
            
                
          const customData = [
            { title: 'One', subtitle: 'Secondary text' },
            { title: 'Two', subtitle: 'Secondary text' },
            { title: 'Three', subtitle: 'Secondary text' },
            { title: 'Four', subtitle: 'Secondary text' },
            { title: 'Five', subtitle: 'Secondary text' },
            { title: 'Six', subtitle: 'Secondary text' },
          ];
    
          const customFilter = (value) => {
            return customData.filter((item) => {
              return item.title.toLowerCase().startsWith(value.toLowerCase());
            });
          };
    
          const displayValueAutocomplete = document.querySelector('#displayValue');
    
          new twe.Autocomplete(displayValueAutocomplete, {
            filter: customFilter,
            displayValue: (value) => value.title,
          });
    
          
            
        

    Asynchronous search

    The function passed to the filter option can return a Promise that resolves to an array of results. By default the component expects to receive data as an array of strings. If you want to return an array of objects instead, you can use displayValue option to specify which parameter should be used as a display value of the specific result.

    • HTML
    • javascript
    • umd
            
                
          <div class="relative" data-twe-input-wrapper-init id="async">
            <input
              type="text"
              class="peer block min-h-[auto] w-full rounded border-0 bg-transparent px-3 py-[0.32rem] leading-[1.6] outline-none transition-all duration-200 ease-linear focus:placeholder:opacity-100 peer-focus:text-primary data-[twe-input-state-active]:placeholder:opacity-100 motion-reduce:transition-none dark:text-white dark:placeholder:text-neutral-300 dark:autofill:shadow-autofill dark:peer-focus:text-primary [&:not([data-twe-input-placeholder-active])]:placeholder:opacity-0"
              id="exampleFormControlInput3" />
            <label
              for="exampleFormControlInput3"
              class="pointer-events-none absolute left-3 top-0 mb-0 max-w-[80%] origin-[0_0] truncate pt-[0.37rem] leading-[1.6] text-neutral-500 transition-all duration-200 ease-out peer-focus:-translate-y-[0.9rem] peer-focus:scale-[0.8] peer-focus:text-primary peer-data-[twe-input-focused]:-translate-y-[0.9rem] peer-data-[twe-input-state-active]:-translate-y-[0.9rem] peer-data-[twe-input-focused]:scale-[0.8] peer-data-[twe-input-state-active]:scale-[0.8] peer-data-[twe-input-focused]:text-primary motion-reduce:transition-none dark:text-neutral-400 dark:peer-focus:text-primary"
              >Example label
            </label>
          </div>
          
            
        
            
                
          import { Autocomplete, Input, initTWE } from "tw-elements";
          initTWE({ Input });
    
          const asyncAutocomplete = document.querySelector('#async');
          const asyncFilter = async (query) => {
          const url = `https://swapi.py4e.com/api/people/?search=${encodeURI(query)}`;
          const response = await fetch(url);
    
          const data = await response.json();
            return data.results;
          };
    
          new Autocomplete(asyncAutocomplete, {
            filter: asyncFilter,
            displayValue: (value) => value.name
          });
    
          
            
        
            
                
          const asyncAutocomplete = document.querySelector('#async');
          const asyncFilter = async (query) => {
          const url = `https://swapi.py4e.com/api/people/?search=${encodeURI(query)}`;
          const response = await fetch(url);
          
          const data = await response.json();
            return data.results;
          };
    
          new twe.Autocomplete(asyncAutocomplete, {
            filter: asyncFilter,
            displayValue: (value) => value.name
          });
    
          
            
        

    Threshold

    Use threshold option to specify a minimum number of the characters in the input field needed to perform a search operation.

    • HTML
    • javascript
    • umd
            
                
          <div class="relative" data-twe-input-wrapper-init id="threshold">
            <input
              type="text"
              class="peer block min-h-[auto] w-full rounded border-0 bg-transparent px-3 py-[0.32rem] leading-[1.6] outline-none transition-all duration-200 ease-linear focus:placeholder:opacity-100 peer-focus:text-primary data-[twe-input-state-active]:placeholder:opacity-100 motion-reduce:transition-none dark:text-white dark:placeholder:text-neutral-300 dark:autofill:shadow-autofill dark:peer-focus:text-primary [&:not([data-twe-input-placeholder-active])]:placeholder:opacity-0"
              id="exampleFormControlInput4"
              placeholder="Type 2 characters to search" />
            <label
              for="exampleFormControlInput4"
              class="pointer-events-none absolute left-3 top-0 mb-0 max-w-[80%] origin-[0_0] truncate pt-[0.37rem] leading-[1.6] text-neutral-500 transition-all duration-200 ease-out peer-focus:-translate-y-[0.9rem] peer-focus:scale-[0.8] peer-focus:text-primary peer-data-[twe-input-focused]:-translate-y-[0.9rem] peer-data-[twe-input-state-active]:-translate-y-[0.9rem] peer-data-[twe-input-focused]:scale-[0.8] peer-data-[twe-input-state-active]:scale-[0.8] peer-data-[twe-input-focused]:text-primary motion-reduce:transition-none dark:text-neutral-400 dark:peer-focus:text-primary"
              >Example label
            </label>
          </div>
          
            
        
            
                
          import { Autocomplete, Input, initTWE } from "tw-elements";
          initTWE({ Input });
    
          const data = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight'];
    
          const dataFilter = (value) => {
            return data.filter((item) => {
              return item.toLowerCase().startsWith(value.toLowerCase());
            });
          };
    
          const thresholdAutocomplete = document.querySelector('#threshold');
    
          new Autocomplete(thresholdAutocomplete, {
            filter: dataFilter,
            threshold: 2
          });
    
          
            
        
            
                
          const data = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight'];
    
          const dataFilter = (value) => {
            return data.filter((item) => {
              return item.toLowerCase().startsWith(value.toLowerCase());
            });
          };
    
          const thresholdAutocomplete = document.querySelector('#threshold');
    
          new twe.Autocomplete(thresholdAutocomplete, {
            filter: dataFilter,
            threshold: 2
          });
    
          
            
        

    Custom item template

    The itemContent option allow to display custom HTML in the result list. You can use the listHeight option to modify the result list height when you want to display more content in the component dropdown.

    • HTML
    • javascript
    • umd
            
                
          <div
            class="relative"
            data-twe-input-wrapper-init
            id="customItem"
            data-twe-list-height="295">
            <input
              type="text"
              class="peer block min-h-[auto] dark:autofill:shadow-autofill w-full rounded border-0 bg-transparent px-3 py-[0.32rem] leading-[1.6] outline-none transition-all duration-200 ease-linear focus:placeholder:opacity-100 peer-focus:text-primary data-[twe-input-state-active]:placeholder:opacity-100 motion-reduce:transition-none dark:text-white dark:placeholder:text-neutral-300 dark:peer-focus:text-primary [&:not([data-twe-input-placeholder-active])]:placeholder:opacity-0"
              id="exampleFormControlInput5" />
            <label
              for="exampleFormControlInput5"
              class="pointer-events-none absolute left-3 top-0 mb-0 max-w-[80%] origin-[0_0] truncate pt-[0.37rem] leading-[1.6] text-neutral-500 transition-all duration-200 ease-out peer-focus:-translate-y-[0.9rem] peer-focus:scale-[0.8] peer-focus:text-primary peer-data-[twe-input-focused]:-translate-y-[0.9rem] peer-data-[twe-input-state-active]:-translate-y-[0.9rem] peer-data-[twe-input-focused]:scale-[0.8] peer-data-[twe-input-focused]:text-primary peer-data-[twe-input-state-active]:scale-[0.8] motion-reduce:transition-none dark:text-neutral-400 dark:peer-focus:text-primary"
              >Example label
            </label>
          </div>
          
            
        
            
                
          import { Autocomplete, Input, initTWE } from "tw-elements";
          initTWE({ Input });
    
          const customData = [
            { title: 'One', subtitle: 'Secondary text' },
            { title: 'Two', subtitle: 'Secondary text' },
            { title: 'Three', subtitle: 'Secondary text' },
            { title: 'Four', subtitle: 'Secondary text' },
            { title: 'Five', subtitle: 'Secondary text' },
            { title: 'Six', subtitle: 'Secondary text' },
          ];
    
          const customFilter = (value) => {
            return customData.filter((item) => {
              return item.title.toLowerCase().startsWith(value.toLowerCase());
            });
          };
    
          const customItem = document.querySelector('#customItem');
    
          new Autocomplete(customItem, {
            filter: customFilter,
            displayValue: (value) => value.title,
            itemContent: (result) => {
              return `
              <div class="flex flex-col">
                <div class="font-medium">${result.title}</div>
                <div class="text-[0.9rem]">${result.subtitle}</div>
              </div>
            `;
            },
          });
          
            
        
            
                
          const customData = [
            { title: 'One', subtitle: 'Secondary text' },
            { title: 'Two', subtitle: 'Secondary text' },
            { title: 'Three', subtitle: 'Secondary text' },
            { title: 'Four', subtitle: 'Secondary text' },
            { title: 'Five', subtitle: 'Secondary text' },
            { title: 'Six', subtitle: 'Secondary text' },
          ];
    
          const customFilter = (value) => {
            return customData.filter((item) => {
              return item.title.toLowerCase().startsWith(value.toLowerCase());
            });
          };
    
          const customItem = document.querySelector('#customItem');
    
          new twe.Autocomplete(customItem, {
            filter: customFilter,
            displayValue: (value) => value.title,
            itemContent: (result) => {
              return `
              <div class="flex flex-col">
                <div class="font-medium">${result.title}</div>
                <div class="text-[0.9rem]">${result.subtitle}</div>
              </div>
            `;
            },
          });
          
            
        

    Custom content

    A custom content container with a data-twe-autocomplete-custom-content-ref attribute will be displayed at the end of the autocomplete dropdown. You can use it to display a number of search results.

    • HTML
    • javascript
    • umd
            
                
          <div class="relative" data-twe-input-wrapper-init id="customContent">
            <input
              type="text"
              class="peer block min-h-[auto] w-full rounded border-0 bg-transparent px-3 py-[0.32rem] leading-[1.6] outline-none transition-all duration-200 ease-linear focus:placeholder:opacity-100 peer-focus:text-primary data-[twe-input-state-active]:placeholder:opacity-100 motion-reduce:transition-none dark:text-white dark:placeholder:text-neutral-300 dark:autofill:shadow-autofill dark:peer-focus:text-primary [&:not([data-twe-input-placeholder-active])]:placeholder:opacity-0"
              id="exampleFormControlInput6" />
            <label
              for="exampleFormControlInput6"
              class="pointer-events-none absolute left-3 top-0 mb-0 max-w-[80%] origin-[0_0] truncate pt-[0.37rem] leading-[1.6] text-neutral-500 transition-all duration-200 ease-out peer-focus:-translate-y-[0.9rem] peer-focus:scale-[0.8] peer-focus:text-primary peer-data-[twe-input-focused]:-translate-y-[0.9rem] peer-data-[twe-input-state-active]:-translate-y-[0.9rem] peer-data-[twe-input-focused]:scale-[0.8] peer-data-[twe-input-focused]:text-primary peer-data-[twe-input-state-active]:scale-[0.8] motion-reduce:transition-none dark:text-neutral-400 dark:peer-focus:text-primary"
              >Example label
            </label>
          </div>
          
            
        
            
                
          import { Autocomplete, Input, initTWE } from "tw-elements";
          initTWE({ Input });
    
          const data = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight'];
    
          const dataFilter = (value) => {
            return data.filter((item) => {
              return item.toLowerCase().startsWith(value.toLowerCase());
            });
          };
    
          const customContent = document.querySelector('#customContent');
    
          new Autocomplete(customContent, {
            filter: dataFilter,
            customContent: `
            <div data-twe-autocomplete-custom-content-ref class="px-4 py-1.5"></div>
          `,
          });
        
          customContent.addEventListener("update.twe.autocomplete", (event) => {
            const resultsLength = event.results.length;
        
            setTimeout(() => {
              const customContentContainer = document.querySelector(
                "[data-twe-autocomplete-custom-content-ref]"
              );
              customContentContainer.innerHTML = `Search results: ${resultsLength}`;
            }, 0);
          });
          
            
        
            
                
          const data = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight'];
    
          const dataFilter = (value) => {
            return data.filter((item) => {
              return item.toLowerCase().startsWith(value.toLowerCase());
            });
          };
    
          const customContent = document.querySelector('#customContent');
    
          new twe.Autocomplete(customContent, {
            filter: dataFilter,
            customContent: `
            <div data-twe-autocomplete-custom-content-ref class="px-4 py-1.5"></div>
          `,
          });
        
          customContent.addEventListener("update.twe.autocomplete", (event) => {
            const resultsLength = event.results.length;
        
            setTimeout(() => {
              const customContentContainer = document.querySelector(
                "[data-twe-autocomplete-custom-content-ref]"
              );
              customContentContainer.innerHTML = `Search results: ${resultsLength}`;
            }, 0);
          });
          
            
        

    Validation

    You can use the validation component together with autocomplete.

    • HTML
    • javascript
    • umd
            
                
          <form
            data-twe-validation-init
            data-twe-active-validation="true"
            autocomplete="off">
            <div
              class="relative"
              id="validation"
              data-twe-input-wrapper-init
              data-twe-validate="input"
              data-twe-validation-ruleset="isRequired">
              <input
                type="text"
                class="peer block min-h-[auto] w-full rounded border-0 bg-transparent px-3 py-[0.32rem] leading-[1.6] outline-none transition-all duration-200 ease-linear focus:placeholder:opacity-100 peer-focus:text-primary data-[twe-input-state-active]:placeholder:opacity-100 motion-reduce:transition-none dark:text-white dark:placeholder:text-neutral-300 dark:autofill:shadow-autofill dark:peer-focus:text-primary [&:not([data-twe-input-placeholder-active])]:placeholder:opacity-0"
                id="exampleFormControlInput7" />
              <label
                for="exampleFormControlInput7"
                class="pointer-events-none absolute left-3 top-0 mb-0 max-w-[80%] origin-[0_0] truncate pt-[0.37rem] leading-[1.6] text-neutral-500 transition-all duration-200 ease-out peer-focus:-translate-y-[0.9rem] peer-focus:scale-[0.8] peer-focus:text-primary peer-data-[twe-input-focused]:-translate-y-[0.9rem] peer-data-[twe-input-state-active]:-translate-y-[0.9rem] peer-data-[twe-input-focused]:scale-[0.8] peer-data-[twe-input-state-active]:scale-[0.8] peer-data-[twe-input-focused]:text-primary motion-reduce:transition-none dark:text-neutral-400 dark:peer-focus:text-primary"
                >Example label
              </label>
            </div>
            <button
              type="button"
              class="mt-5 inline-block rounded bg-primary px-6 pb-2 pt-2.5 text-xs font-medium uppercase leading-normal text-white shadow-primary-3 transition duration-150 ease-in-out hover:bg-primary-accent-300 hover:shadow-primary-2 focus:bg-primary-accent-300 focus:shadow-primary-2 focus:outline-none focus:ring-0 active:bg-primary-600 active:shadow-primary-2 dark:shadow-black/30 dark:hover:shadow-dark-strong dark:focus:shadow-dark-strong dark:active:shadow-dark-strong"
              data-twe-submit-btn-ref>
              Submit
            </button>
          </form>
          
            
        
            
                
          import { Autocomplete, Input, Validation, initTWE } from "tw-elements";
    
          initTWE({ Input, Validation })
    
          const data = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight'];
    
          const dataFilter = (value) => {
            return data.filter((item) => {
              return item.toLowerCase().startsWith(value.toLowerCase());
            });
          };
    
          const validationAutocomplete = document.querySelector('#validation');
    
          new Autocomplete(validationAutocomplete, {
            filter: dataFilter
          });
    
          
            
        
            
                
          const data = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight'];
    
          const dataFilter = (value) => {
            return data.filter((item) => {
              return item.toLowerCase().startsWith(value.toLowerCase());
            });
          };
    
          const validationAutocomplete = document.querySelector('#validation');
    
          new twe.Autocomplete(validationAutocomplete, {
            filter: dataFilter
          });
    
          
            
        

    Auto select

    Set autoSelect option to true to enable selecting on Tab press.

    • HTML
    • javascript
    • umd
            
                
          <div class="relative" id="auto-select" data-twe-input-wrapper-init>
            <input
              type="text"
              class="peer block min-h-[auto] w-full rounded border-0 bg-transparent px-3 py-[0.32rem] leading-[1.6] outline-none transition-all duration-200 ease-linear focus:placeholder:opacity-100 peer-focus:text-primary data-[twe-input-state-active]:placeholder:opacity-100 motion-reduce:transition-none dark:text-white dark:placeholder:text-neutral-300 dark:autofill:shadow-autofill dark:peer-focus:text-primary [&:not([data-twe-input-placeholder-active])]:placeholder:opacity-0"
              id="exampleFormControlInput8" />
            <label
              for="exampleFormControlInput8"
              class="pointer-events-none absolute left-3 top-0 mb-0 max-w-[80%] origin-[0_0] truncate pt-[0.37rem] leading-[1.6] text-neutral-500 transition-all duration-200 ease-out peer-focus:-translate-y-[0.9rem] peer-focus:scale-[0.8] peer-focus:text-primary peer-data-[twe-input-focused]:-translate-y-[0.9rem] peer-data-[twe-input-state-active]:-translate-y-[0.9rem] peer-data-[twe-input-focused]:scale-[0.8] peer-data-[twe-input-state-active]:scale-[0.8] peer-data-[twe-input-focused]:text-primary motion-reduce:transition-none dark:text-neutral-400 dark:peer-focus:text-primary"
              >Example label
            </label>
          </div>
          
            
        
            
                
          import { Autocomplete, Input, initTWE } from "tw-elements";
          initTWE({ Input });
    
          const data = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight'];
    
          const dataFilter = (value) => {
            return data.filter((item) => {
              return item.toLowerCase().startsWith(value.toLowerCase());
            });
          };
    
          const autoSelectAutocomplete = document.querySelector('#auto-select');
    
          new Autocomplete(autoSelectAutocomplete, {
            filter: dataFilter,
            autoSelect: true
          });
    
          
            
        
            
                
          const data = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight'];
    
          const dataFilter = (value) => {
            return data.filter((item) => {
              return item.toLowerCase().startsWith(value.toLowerCase());
            });
          };
    
          const autoSelectAutocomplete = document.querySelector('#auto-select');
    
          new twe.Autocomplete(autoSelectAutocomplete, {
            filter: dataFilter,
            autoSelect: true
          });
    
          
            
        

    Related resources

    Tutorials:

    spacing utility first rounded corners lists sizing inputs forms

    Extended Docs:

    hover effects icons mega menu navbar offcanvas scrollspy buttons cards dropdown listgroup modal datepicker file input form templates inputs login form registration form search timepicker borders center grid items dark theme display flex position spacing

    Generators and builders:

    Form drag & drop Typography SVG icon Instagram Filters button card table flexbox logo grid footer

    Design System (Figma):

    introduction art of prioritization de emphasize with no mercy lowering contrast beyond borders let it breathe user experience do not start with the roof secondary questions project personality design system principles tips and tricks
    • Basic example
    • Display value
    • Asynchronous search
    • Threshold
    • Custom item template
    • Custom content
    • Validation
    • Auto select
    • Related resources

    Autocomplete - API


    Import

    Importing components depends on how your application works. If you intend to use the TW elements ES format, you can import the component and then create a new instance with it. If you are going to use the UMD format, just import the tw-elements package.

    • javascript
    • umd
            
                
            import { Autocomplete } from "tw-elements";
            
            
        
            
                
            import "tw-elements";
            
            
        

    Usage

    Via JavaScript

    You can access an instance from your Javascript code, by using the getInstance static method of the Autocomplete class - it allows making use of all the public methods listed in the Methods section.

    • javascript
    • umd
            
                
            const basicAutocomplete = document.querySelector('#basic');
            
            new Autocomplete(basicAutocomplete, {
              filter: dataFilter,
            });
            
            
        
            
                
            const basicAutocomplete = document.querySelector('#basic');
            
            new twe.Autocomplete(basicAutocomplete, {
              filter: dataFilter,
            });
            
            
        

    Options

    Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-twe-, as in data-twe-no-results="No results ...".

    Name Type Default Description
    autoSelect Boolean false Enables auto selecting on Tab press.
    container String 'body' Allows to set the parent element for the autocomplete.
    customContent String '' Custom HTML template that will be displayed at the end of the component dropdown.
    debounce Number 300 Delay between search queries in milliseconds, improves the component performance.
    displayValue Function (value) => value Function executed for complex search results, to get value to display in the results list.
    filter Function - Function that returns filtered data to the component.
    itemContent Function - Function that returns custom template for result item.
    listHeight Number 190 Height of the result list.
    loaderCloseDelay Number 300 Delay in closing loader.
    noResults String 'No results found' Message that will be displayed in the component dropdown if no result is found.
    offset Array | String | Function [0,1]

    Offset of the dropdown relative to its target.

    When a function is used to determine the offset, it is called with an object containing the offset data as its first argument. The function must return an object with the same structure. The triggering element DOM node is passed as the second argument.

    For more information refer to Popper's offset docs.

    threshold Number 0 Minimum input length to start search query.

    Classes

    Custom classes can be passed via data attributes or JavaScript. For data attributes, append the class name to data-twe-class, as in data-twe-class-autocomplete-list="list-none m-0 p-0 overflow-y-auto"

    Note: To apply styling to an input element, you can utilize the identical classes as those available in the Inputs API.
    Name Default Description
    autocompleteItem flex flex-row items-center justify-between w-full px-4 py-[0.4375rem] truncate text-gray-700 bg-transparent select-none cursor-pointer hover:[&:not([data-twe-autocomplete-option-disabled])]:bg-black/5 data-[twe-autocomplete-item-active]:bg-black/5 data-[data-twe-autocomplete-option-disabled]:text-surface/50 data-[data-twe-autocomplete-option-disabled]:cursor-default dark:text-white dark:hover:[&:not([data-twe-autocomplete-option-disabled])]:bg-black/10 dark:data-[twe-autocomplete-item-active]:bg-black/10 dark:data-[data-twe-autocomplete-option-disabled]:text-white/50 Classes applied to each result item in the dropdown list.
    autocompleteList list-none m-0 p-0 overflow-y-auto Classes applied to the dropdown list.
    autocompleteLoader absolute end-1 top-2 w-[1.4rem] h-[1.4rem] border-[0.15em] Classes applied to the loader element (async).
    dropdown relative outline-none min-w-[100px] m-0 scale-y-[0.8] opacity-0 bg-white shadow-select transition duration-200 motion-reduce:transition-none data-[twe-autocomplete-state-open]:scale-y-100 data-[twe-autocomplete-state-open]:opacity-100 dark:bg-surface-dark Classes applied to the dropdown element.
    dropdownContainer z-[1070] Classes applied to the dropdown container.
    scrollbar [&::-webkit-scrollbar]:w-1 [&::-webkit-scrollbar]:h-1 [&::-webkit-scrollbar-button]:block [&::-webkit-scrollbar-button]:h-0 [&::-webkit-scrollbar-button]:bg-transparent [&::-webkit-scrollbar-track-piece]:bg-transparent [&::-webkit-scrollbar-track-piece]:rounded-none [&::-webkit-scrollbar-track-piece]: [&::-webkit-scrollbar-track-piece]:rounded-s [&::-webkit-scrollbar-thumb]:h-[50px] [&::-webkit-scrollbar-thumb]:bg-[#999] [&::-webkit-scrollbar-thumb]:rounded [&::-webkit-scrollbar-thumb]:dark:bg-gray-200 Classes applied to the dropdown container. Contains styling for the scrollbar element.
    spinnerIcon inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-current border-e-transparent align-[-0.125em] motion-reduce:animate-[spin_1.5s_linear_infinite] Sets styles for the spinner icon. Contains the animation and the main appearance of the spinner.

    Methods

    Asynchronous methods and transitions:
    All API methods are asynchronous and start a transition. They return to the caller as soon as the transition is started but before it ends. In addition, a method call on a transitioning component will be ignored.

    Method Description Example
    open Manually opens a component dropdown myAutocomplete.open()
    close Manually closes a component dropdown myAutocomplete.close()
    dispose Disposes an autocomplete instance myAutocomplete.dispose()
    getInstance Static method which allows you to get the autocomplete instance associated to a DOM element. Autocomplete.getInstance(myAutocomplete)
    getOrCreateInstance Static method which returns the autocomplete instance associated to a DOM element or create a new one in case it wasn't initialized. Autocomplete.getOrCreateInstance(myAutocomplete)
    initSearch(value) Initialize search results for a specific value. myAutocomplete.initSearch('')
    • javascript
    • umd
            
                
            const myAutocomplete = document.getElementById('myAutocomplete')
            const autocomplete = new Autocomplete(myAutocomplete)
            autocomplete.open()
            
            
        
            
                
            const myAutocomplete = document.getElementById('myAutocomplete')
            const autocomplete = new twe.Autocomplete(myAutocomplete)
            autocomplete.open()
            
            
        

    Events

    Event type Description
    open.twe.autocomplete This event fires immediately when the autocomplete dropdown is opened.
    close.twe.autocomplete This event fires immediately when the autocomplete dropdown is closed.
    itemSelect.twe.autocomplete This event fires immediately when the autocomplete item is selected.
    update.twe.autocomplete This event fires immediately when the autocomplete results list is updated.
    • JavaScript
            
                
            const myAutocomplete = document.getElementById('myAutocomplete')
            myAutocomplete.addEventListener('open.twe.autocomplete', (e) => {
              // do something...
            })
            
            
        
    • Import
    • Usage
    • Options
    • Classes
    • Methods
    • Events
    Get useful tips & free resources directly to your inbox along with exclusive subscriber-only content.
    Join our mailing list now
    © 2024 Copyright: MDBootstrap.com

    Access restricted

    To view this section you must have an active PRO account

    Log in to your account or purchase an TWE subscription if you don't have one.

    Buy TWE PRO