Linked Dropdowns

Edit on Github
Open in Playground View Demo

Introduction

These linked dropdowns are implemented using AMP components. This pattern is useful when the values in the second dropdown depend on the value the user selects in the first dropdown. Here we select cities in a chosen country.

Setup

First we include amp-bind to track the page state and update the `<amp-list> data source.

<script async custom-element="amp-bind" src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>

Next we include amp-list to request and display the dropdowns and their options.

<script async custom-element="amp-list" src="https://cdn.ampproject.org/v0/amp-list-0.1.js"></script>

Finally, we include amp-mustache to render the mustache templates inside the <amp-list>s.

<script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.1.js"></script>

Usage

We use two <amp-list> elements to render the options within each <select>. The first dropdown triggers a request, which is batched with the request triggered by the other <amp-list> and the <amp-state> element, so only one request is sent.

When the user selects a value in the first dropdown, amp-bind updates the cities state value. This updates second <amp-list>'s [src] binding, and it renders its template using the data in the cities array.

Example

  <amp-list width="auto"
    height="25"
    layout="fixed-height"
    src="https://ampbyexample.com/json/linked_dropdowns.json">
    <template type="amp-mustache">
      <label for="country">Country:</label>
      <select id="country"
        on="
      change:
        AMP.setState({
          cities: dropdown.items[0].countries.filter(x => x.name == event.value)[0]
        })">
        <option value="">Choose a country</option>
        {{#countries}}
        <option value="{{name}}">{{name}}</option>
        {{/countries}}
      </select>
    </template>
  </amp-list>
  <amp-list width="auto"
    height="25"
    layout="fixed-height"
    [src]="cities || 'https://ampbyexample.com/json/linked_dropdowns.json'"
    src="https://ampbyexample.com/json/linked_dropdowns.json">
    <template type="amp-mustache">
      <label for="city">City:</label>
      <select [disabled]="!cities"
        disabled
        id="city">
        {{^cities}}
        <option value=""></option>{{/cities}} {{#cities.0}}
        <option value="">Choose a city</option>{{/cities.0}} {{#cities}}
        <option value="{{.}}">{{.}}</option>{{/cities}}
      </select>
    </template>
  </amp-list>
  <amp-state id="dropdown"
    src="https://ampbyexample.com/json/linked_dropdowns.json"></amp-state>