candidate

Autocomplete

An example of how to use the autocomplete module.



<div class="autocomplete__wrapper">

<div class="govuk-form-group govuk-!-margin-top-2">
  <label class="govuk-label" for="organisation-search">
    Search for an organisation
  </label>
  <span id="organisation-search-error" class="govuk-error-message" role="alert">
    <span class="govuk-visually-hidden">Error:</span> Value entered not recognised, please try again
  </span>
  <select class="govuk-select" id="organisation-search" name="organisation-search">
    <option value=""></option>
  </select>
</div>

</div>
{%- from "design-system/components/autocomplete/macro.html" import dlAutocomplete %}

<div class="autocomplete__wrapper">
  {{ dlAutocomplete({
    "name": "organisation-search",
    "label": "Search for an organisation",
    "classes": "govuk-!-margin-top-2",
    "data": organisation_data
  }) }}
</div>

Include the assets

Need to include the required js and css.

Add the css to the page head. For example

<link href="/design-system/static/stylesheets/vendor/govuk-accessible-autocomplete.min.css" rel="stylesheet" media="all" />

Add the js to end of the <body>. For example

<script src="/design-system/static/javascripts/vendor/govuk-accessible-autocomplete.min.js"></script>
<script>
    const $picker = document.querySelector('#organisation-search')
    accessibleAutocomplete.enhanceSelectElement({
        selectElement: $picker
    })
</script>