Visit lgs1920.fr

@lgs1920/autocomplete · Web Awesome 3

Search, choose, keep the real value

Search local data or connect a live API. Keep the selected value your forms need while showing people clear labels, icons, and useful metadata.

Read the API View source

Examples

Try the component

Type a few letters, move through results with the arrow keys, and press Enter to select. Each item can keep domain fields alongside its value and label. The city example shows per-instance input styles; the brand example previews standard theme colors.

Local options · recent selections · default appearance

Find a fruit

Choose from 30 fruits in English. The last three selections are saved in this browser and shown when the field is empty. With recent suggestions open, activate the chevron to show every fruit; it points up while the full list is open. The field uses the component's default size and appearance, with the active theme's standard colors.

Clear selection
Nothing selected
View example code

HTML

<lgs1920-autocomplete id="local-autocomplete" label="Fruit" name="fruit" with-clear>
    <wa-icon slot="start" name="magnifying-glass" aria-hidden="true"></wa-icon>
</lgs1920-autocomplete>

JavaScript

const field = document.querySelector('#local-autocomplete')
field.options = [
  {value: 'apple', label: 'Apple', category: 'Pome fruit'},
  {value: 'apricot', label: 'Apricot', category: 'Stone fruit'},
  {value: 'avocado', label: 'Avocado', category: 'Tropical fruit'},
  {value: 'banana', label: 'Banana', category: 'Tropical fruit'},
  {value: 'blackberry', label: 'Blackberry', category: 'Berry'},
  {value: 'blueberry', label: 'Blueberry', category: 'Berry'},
  {value: 'cantaloupe', label: 'Cantaloupe', category: 'Melon'},
  {value: 'cherry', label: 'Cherry', category: 'Stone fruit'},
  {value: 'coconut', label: 'Coconut', category: 'Tropical fruit'},
  {value: 'cranberry', label: 'Cranberry', category: 'Berry'},
  {value: 'dragon-fruit', label: 'Dragon fruit', category: 'Tropical fruit'},
  {value: 'fig', label: 'Fig', category: 'Tropical fruit'},
  {value: 'grape', label: 'Grape', category: 'Berry'},
  {value: 'grapefruit', label: 'Grapefruit', category: 'Citrus fruit'},
  {value: 'guava', label: 'Guava', category: 'Tropical fruit'},
  {value: 'kiwi', label: 'Kiwi', category: 'Tropical fruit'},
  {value: 'lemon', label: 'Lemon', category: 'Citrus fruit'},
  {value: 'lime', label: 'Lime', category: 'Citrus fruit'},
  {value: 'mango', label: 'Mango', category: 'Tropical fruit'},
  {value: 'nectarine', label: 'Nectarine', category: 'Stone fruit'},
  {value: 'orange', label: 'Orange', category: 'Citrus fruit'},
  {value: 'papaya', label: 'Papaya', category: 'Tropical fruit'},
  {value: 'peach', label: 'Peach', category: 'Stone fruit'},
  {value: 'pear', label: 'Pear', category: 'Pome fruit'},
  {value: 'pineapple', label: 'Pineapple', category: 'Tropical fruit'},
  {value: 'plum', label: 'Plum', category: 'Stone fruit'},
  {value: 'pomegranate', label: 'Pomegranate', category: 'Pome fruit'},
  {value: 'raspberry', label: 'Raspberry', category: 'Berry'},
  {value: 'strawberry', label: 'Strawberry', category: 'Berry'},
  {value: 'watermelon', label: 'Watermelon', category: 'Melon'},
]
field.persistence = {id: 'fruit-search-demo', limit: 3}

field.addEventListener('wa-select', event => {
  console.log(event.detail.value, event.detail.option.category)
})
Close

Local options · HTML template

Render cities from a template

Type a city name to try the custom suggestion layout. Each option uses the HTML template below the field; select one to inspect its value and metadata.

Nothing selected
View example code

HTML

<template id="city-option-template">
  <wa-card appearance="outlined">
    <strong>{{city}}</strong>
    <small>{{region}} · {{country}}</small>
  </wa-card>
</template>

<lgs1920-autocomplete id="template-autocomplete" label="City" name="templateCity" option-template="city-option-template"></lgs1920-autocomplete>

JavaScript

const field = document.querySelector('#template-autocomplete')
field.options = [
  {value: 'paris', label: 'Paris', city: 'Paris', region: 'Île-de-France', country: 'France'},
  {value: 'reims', label: 'Reims', city: 'Reims', region: 'Grand Est', country: 'France'},
  {value: 'lyon', label: 'Lyon', city: 'Lyon', region: 'Auvergne-Rhône-Alpes', country: 'France'},
]
Close

Local options · Web Awesome brand colors

Choose a brand color

Choose a standard Web Awesome brand hue to change the active brand for the whole demo. The field, suggestions, preview, and other brand-colored controls update together.

Choose a color to preview Background: --wa-color-brand-fill-loud Text: --wa-color-brand-on-loud
View example code

HTML

<lgs1920-autocomplete id="brand-color-autocomplete" class="autocomplete-brand" label="Brand color" name="brandColor" appearance="filled-outlined" with-clear>
  <wa-icon slot="start" name="palette" aria-hidden="true"></wa-icon>
</lgs1920-autocomplete>
<div id="brand-color-preview" class="brand-color-preview">
  <strong>Selected brand hue</strong>
  </div>

CSS

.brand-color-preview {
  padding: var(--wa-space-l);
  border-radius: var(--wa-border-radius-l);
  background: var(--wa-color-surface-raised);
  color: var(--wa-color-text-normal);
}

.brand-color-preview--selected {
  background: var(--wa-color-brand-fill-loud);
  color: var(--wa-color-brand-on-loud);
}

.autocomplete-brand {
  color: var(--wa-color-brand-on-quiet);
  --wa-color-focus: var(--wa-color-brand-border-loud);
  --wa-form-control-label-color: var(--wa-color-brand-on-quiet);
  --wa-form-control-value-color: var(--wa-color-brand-on-quiet);
  /* Tint the suggestion panel with the current brand hue. */
  --lgs1920-autocomplete-panel-background: var(--wa-color-brand-fill-quiet);
  /* Keep panel messages legible on the brand surface. */
  --lgs1920-autocomplete-panel-color: var(--wa-color-brand-on-quiet);
  /* Mark the panel edge with a stronger brand tone. */
  --lgs1920-autocomplete-panel-border-color: var(--wa-color-brand-border-loud);
  /* Match regular option text to the quiet brand surface. */
  --lgs1920-autocomplete-option-color: var(--wa-color-brand-on-quiet);
  /* Give the keyboard-active option a stronger brand surface. */
  --lgs1920-autocomplete-option-active-background: var(--wa-color-brand-fill-normal);
  /* Keep pointer hover within the brand palette. */
  --lgs1920-autocomplete-option-hover-background: var(--wa-color-brand-fill-quiet);
  /* Use the loud brand fill for a selected option. */
  --lgs1920-autocomplete-option-selected-background: var(--wa-color-brand-fill-loud);
  /* Use the matching on-color text for contrast. */
  --lgs1920-autocomplete-option-selected-color: var(--wa-color-brand-on-loud);
  /* Tint option icons with the current brand hue. */
  --lgs1920-autocomplete-option-icon-color: var(--wa-color-brand-on-quiet);
  /* Color the input outline and focus state with the chosen brand hue. */
  --wa-form-control-border-color: var(--wa-color-brand-border-loud);
  --wa-form-control-activated-color: var(--wa-color-brand-fill-loud);
  /* Tint the filled input surface with the chosen brand hue. */
  --wa-color-neutral-fill-quiet: var(--wa-color-brand-fill-quiet);
  /* Keep the input placeholder within the chosen brand palette. */
  --lgs1920-autocomplete-placeholder-color: var(--wa-color-brand-on-quiet);
}

JavaScript

const field = document.querySelector('#brand-color-autocomplete')
const root = document.documentElement
const brandControl = document.querySelector('#brand-control')
const preview = document.querySelector('#brand-color-preview')
const previewName = document.querySelector('#brand-color-preview-name')
const hues = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'indigo', 'purple', 'pink', 'gray']
field.options = hues.map(hue => ({value: hue, label: hue}))
const updatePreview = option => {
  if (!option) return
  const brandClasses = hues.map(hue => 'wa-brand-' + hue)
  root.classList.remove(...brandClasses)
  root.classList.add('wa-brand-' + option.value)
  brandControl.value = option.value
  preview.classList.add('brand-color-preview--selected')
  previewName.textContent = option.label + ' brand'
}
field.addEventListener('wa-select', event => updatePreview(event.detail.option))
field.addEventListener('wa-clear', () => updatePreview())
Close

Photon · cyan filled-outlined style

Search cities

Searches Photon cities and localities live after two characters and waits 350 ms after the last keystroke. Each suggestion uses a card with the city, department, region, and country on separate lines when available. Photon is asked for up to 32 matches, shown eight per page. When another page exists, the footer shows the page size, current page and page count, and Web Awesome pagination controls. This larger filled-outlined field uses cyan tokens for its suggestion panel and option states.

Nothing selected
View example code

HTML

<lgs1920-autocomplete id="remote-autocomplete" class="autocomplete-cyan" label="City" size="l" appearance="filled-outlined" min-chars="2" debounce="350" page-size="8" max-results="32"></lgs1920-autocomplete>

CSS

.autocomplete-cyan {
    /* Blend the panel with the active theme's raised surface. */
    --lgs1920-autocomplete-panel-background: color-mix(in srgb, var(--wa-color-surface-raised) 88%, var(--wa-color-cyan) 12%);
    /* Follow the active theme's text color. */
    --lgs1920-autocomplete-panel-color: var(--wa-color-text-normal);
    /* Blend the outline with the active theme's border color. */
    --lgs1920-autocomplete-panel-border-color: color-mix(in srgb, var(--wa-color-surface-border) 70%, var(--wa-color-cyan) 30%);
    /* Tint the keyboard-active option. */
    --lgs1920-autocomplete-option-active-background: color-mix(in srgb, var(--wa-color-surface-raised) 76%, var(--wa-color-cyan) 24%);
    /* Tint the pointer-hover option. */
    --lgs1920-autocomplete-option-hover-background: color-mix(in srgb, var(--wa-color-surface-raised) 86%, var(--wa-color-cyan) 14%);
    /* Apply a stronger cyan tint to the selected option. */
    --lgs1920-autocomplete-option-selected-background: color-mix(in srgb, var(--wa-color-surface-raised) 68%, var(--wa-color-cyan) 32%);
    /* Keep selected-option text readable in each color mode. */
    --lgs1920-autocomplete-option-selected-color: var(--wa-color-text-normal);
    /* Tint icons with cyan and the active theme's quiet text color. */
    --lgs1920-autocomplete-option-icon-color: color-mix(in srgb, var(--wa-color-text-quiet) 40%, var(--wa-color-cyan) 60%);
}

JavaScript

/**
 * Format a Photon place with its city, department, region, and country.
 * @param {object} place - Photon place properties.
 */
const formatCityLabel = place => [...new Set([place.name, place.county, place.state, place.country].filter(Boolean))].join(', ')

const field = document.querySelector('#remote-autocomplete')
field.renderOption = option => {
  const card = document.createElement('wa-card')
  card.setAttribute('appearance', 'outlined')
  for (const [label, value] of [
    ['City', option.city],
    ['Department', option.department],
    ['Region', option.region],
    ['Country', option.country],
  ]) {
    if (!value) continue
    const line = document.createElement('div')
    const name = document.createElement('strong')
    name.textContent = `${label}: `
    const fieldValue = document.createElement('span')
    fieldValue.textContent = value
    line.append(name, fieldValue)
    card.append(line)
  }
  return card
}

field.searchOptions = async (query, {signal}) => {
  const endpoint = new URL('https://photon.komoot.io/api/')
  endpoint.searchParams.set('q', query.trim())
  endpoint.searchParams.set('limit', String(field.maxResults))
  endpoint.searchParams.set('lang', 'en')
  endpoint.searchParams.append('layer', 'city')
  endpoint.searchParams.append('layer', 'locality')
  const response = await fetch(endpoint, {signal})
  if (!response.ok) throw new Error('City search failed')
  const result = await response.json()
  return result.features.map(feature => {
    const place = feature.properties
    return {
      value: `${place.osm_type}/${place.osm_id}`,
      label: formatCityLabel(place),
      city: place.name,
      department: place.county,
      region: place.state,
      country: place.country,
      countryCode: place.countrycode,
      latitude: feature.geometry.coordinates[1],
      longitude: feature.geometry.coordinates[0],
    }
  })
}
Close

Remote options · multiple selection · country flags

Choose country flags

Searches countries.dev by name and loads flags from FlagCDN. Flags appear as icons in suggestions and selected tags; selected flags are also shown below. Each ISO code is submitted under the same form field name. If the tags overflow, activate +N to browse all selections, 10 per page.

No countries selected
View example code

HTML

<lgs1920-autocomplete id="multiple-autocomplete" name="country-code" multiple label="Countries" min-chars="3" page-size="10" max-results="50" with-clear></lgs1920-autocomplete>
<div id="multiple-autocomplete-selection" class="selected-flags" role="status" aria-live="polite">
    <span class="selected-flags-empty">No countries selected</span>
</div>
<wa-details id="multiple-autocomplete-response-details" class="country-response-details" summary="View response" hidden>
    <pre class="search-result" data-language="JSON" role="status" aria-live="polite"><code id="multiple-autocomplete-response"></code></pre>
</wa-details>

JavaScript

const field = document.querySelector('#multiple-autocomplete')
const responseDetails = document.querySelector('#multiple-autocomplete-response-details')
const responseOutput = document.querySelector('#multiple-autocomplete-response')
field.searchOptions = async (query, {signal}) => {
  responseDetails.hidden = true
  responseOutput.replaceChildren()
  const endpoint = new URL('https://countries.dev/name/' + encodeURIComponent(query.trim()))
  endpoint.searchParams.set('fields', 'name,alpha2Code,flag,flags')
  endpoint.searchParams.set('limit', String(field.maxResults))
  const response = await fetch(endpoint, {signal})
  if (response.status === 404) {
    responseOutput.textContent = '[]'
    responseDetails.hidden = false
    return []
  }
  if (!response.ok) throw new Error('Country search failed')
  const countries = await response.json()
  responseOutput.textContent = JSON.stringify(countries, null, 2)
  responseDetails.hidden = false
  const countryFlagEmoji = code => Array.from(code.toUpperCase(), letter => String.fromCodePoint(letter.charCodeAt(0) + 127397)).join('')
  return countries.map(country => {
    const flagUrl = 'https://flagcdn.io/' + country.alpha2Code.toLowerCase() + '.svg'
    const flagEmoji = countryFlagEmoji(country.alpha2Code)
    return {
      value: country.alpha2Code,
      label: country.name,
      icon: {src: flagUrl, fallback: flagEmoji},
      flagUrl: flagUrl,
      flagEmoji: flagEmoji,
    }
  })
}

const output = document.querySelector('#multiple-autocomplete-selection')
const renderFlags = () => {
  output.replaceChildren()
  if (field.selectedOptions.length === 0) {
    output.textContent = 'No countries selected'
    return
  }
  field.selectedOptions.forEach(country => {
    const flag = document.createElement('img')
    flag.src = country.flagUrl
    flag.alt = 'Flag of ' + country.label
    output.append(flag)
  })
}
field.addEventListener('wa-select', renderFlags)
field.addEventListener('wa-deselect', renderFlags)
field.addEventListener('wa-clear', renderFlags)
Close

SVG and PNG icons · local and remote URLs

Combine icon sources

Choose from these four places. Each one demonstrates a different icon source; selected places appear in the field and in the list below.

Available places

  • Compass routeLocal SVG file
  • Historic landmarkWeb Awesome icon
  • Old townLocal SVG file
  • FranceRemote FlagCDN SVG
No places selected
View example code

HTML

<div class="available-choices">
  <p>Available places</p>
  <ul>
    <li><strong>Compass route</strong><span>Local SVG file</span></li>
    <li><strong>Historic landmark</strong><span>Web Awesome icon</span></li>
    <li><strong>Old town</strong><span>Local SVG file</span></li>
    <li><strong>France</strong><span>Remote FlagCDN SVG</span></li>
  </ul>
</div>
<lgs1920-autocomplete id="icon-source-autocomplete" name="place" multiple label="Places" icon-position="start" max-options-visible="2" with-clear></lgs1920-autocomplete>
<wa-details summary="Selected places">
  <pre role="status" aria-live="polite"><code id="icon-source-autocomplete-selection">No places selected</code></pre>
</wa-details>

JavaScript · direct URLs

const field = document.querySelector('#icon-source-autocomplete')
field.options = [
  {value: 'compass', label: 'Compass route', icon: '/icons/compass.svg'},
  {value: 'landmark', label: 'Historic landmark', icon: 'landmark'},
  {value: 'old-town', label: 'Old town', icon: {src: '/icons/landmark.svg'}},
  {value: 'france', label: 'France', icon: {src: 'https://flagcdn.io/fr.svg', fallback: '🇫🇷'}},
]

JavaScript · Vite glob

const iconUrls = import.meta.glob('../icons/*.{svg,png}', {
  eager: true,
  import: 'default',
  query: '?url',
})

field.options = Object.entries(iconUrls).map(([path, src]) => ({
  value: path,
  label: path.split('/').pop(),
  icon: {src},
}))
Close

countries.dev · form-associated value

Submit a country code

Submit country code
Search for a country, then submit the form.

Searches countries.dev by name and submits the selected ISO alpha-2 country code.

View example code

HTML

<form id="form-demo">
    <lgs1920-autocomplete id="form-autocomplete" name="country-code" label="Country" min-chars="3"></lgs1920-autocomplete>
    <wa-button type="submit">Submit country code</wa-button>
</form>

JavaScript

const field = document.querySelector('#form-autocomplete')
field.searchOptions = async (query, {signal}) => {
  const endpoint = new URL(`https://countries.dev/name/${encodeURIComponent(query.trim())}`)
  endpoint.searchParams.set('fields', 'name,alpha2Code')
  endpoint.searchParams.set('limit', String(field.maxResults))
  const response = await fetch(endpoint, {signal})
  if (response.status === 404) return []
  if (!response.ok) throw new Error('Country search failed')
  const countries = await response.json()
  return countries.map(country => ({
    value: country.alpha2Code,
    label: country.name,
  }))
}

const form = document.querySelector('#form-demo')
form.addEventListener('submit', event => {
  event.preventDefault()
  const data = Object.fromEntries(new FormData(event.currentTarget).entries())
  console.log(data)
})
Close

Quick start

Add the field, then provide its options

In a bundled project, the HTML declares initial choices with <wa-option> elements. JavaScript appends Lyon through field.options, showing how to update the list in code. It also remembers recent choices and handles selection and form submission.

See the full options and events reference for the remote search contract, keyboard behavior, and icon formats.