uktrade/lite-forms

View on GitHub
templates/components/autocomplete.html

Summary

Maintainability
Test Coverage
<select id="{{ component.name }}" name="{{ component.name }}" class="govuk-select {% if error %}govuk-select--error{% endif %}">
    <option value="">Select</option>
    {% for item in component.options %}
        <option value="{{ item.key }}" {% if value == item.key %}selected{% endif %}>{{ item.value }}</option>
    {% endfor %}
</select>

<script type="text/javascript" nonce="{{ request.csp_nonce }}">
    {% if component.deferred %}
        function loadAutoCompletes() {
    {% else %}
        $(document).ready(function() {
    {% endif %}
            accessibleAutocomplete.enhanceSelectElement({
                defaultValue: '',
                displayMenu: 'overlay',
                selectElement: document.querySelector('#{{ component.name|prefix_dots }}'),
                cssNamespace: 'lite-autocomplete',
                onConfirm: (val) => {
                    if (val && $("#{{ component.name|prefix_dots }}").val()) {
                        $("#{{ component.name|prefix_dots }}-select option").filter(function() {
                          return $(this).text() != val;
                        }).prop('selected', false);
                        $("#{{ component.name|prefix_dots }}-select option").filter(function() {
                          return $(this).text() == val;
                        }).prop('selected', true);

                    } else if (val == undefined && $("#{{ component.name|prefix_dots }}").val() == "") {
                        $("#{{ component.name|prefix_dots }}-select option").filter(function() {
                          return $(this).text() != val;
                        }).prop('selected', false);
                    }
                }
            });
    {% if component.deferred %}
        }
    {% else %}
        });
    {% endif %}
</script>