Do you build things with AMP? Fill out the AMP Developer Survey!
  • websites

Restrict Duplicate Selection


This is a sample showing how to restrict duplicate selection of items in amp-list. This uses amp-selector in combination with amp-bind to check whether or not an item is currently in the list (populated by fruits list).

If the fruit you select is already in the fruits list, the fruits list doesn't change.

If the fruit you select is not already in the fruits list then it's added to the end of the list.

<!doctype html>
<html >
<meta charset="utf-8">
  <title>Restrict Duplicate Selection</title>
  <link rel="canonical" href="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script async src=""></script>


Import the amp-bind component to hold the selected fruits

<script async custom-element="amp-bind" src=""></script>

Import the amp-list component to import the list of fruits to select from

<script async custom-element="amp-list" src=""></script>

Import the amp-selector component so user can choose fruits

<script async custom-element="amp-selector" src=""></script>

The amp-mustache component is required if using amp-selector with amp-list

<script async custom-template="amp-mustache" src=""></script>


We use the amp-state element to create a list that's initially empty but will update once user selects fruits. User selects fruits from amp-list element (imported from fruits.json file).

Every time the user tries to select a fruit, the amp-selector element will validate whether or not fruit is already in fruits list. If fruit is not already in the list, amp-selector will change the state of the fruits list with the new fruit at end. If fruit is in fruit-selected list, the list stays the same.

Pick your favorite fruites from this list
You can only add new fruits to the list, you can't add the same fruit multiple times.

Select fruits!

<amp-state id="fruits">
  <script type="application/json">
  Pick your favorite fruites from this list <br> You can only add new fruits to the list, you can't add the same fruit
  multiple times.
<div style="resize: horizontal; overflow: auto;">
  <p [text]="fruits">Select fruits!</p>
<amp-list src="/static/samples/json/fruits.json"
  <template type="amp-mustache">
      <amp-selector on="select:AMP.setState({fruits: fruits.includes(event.targetOption) ? fruits : fruits.concat([event.targetOption])})">
          <li option="{{name}}"

如果此页面上的说明未能涵盖您的所有问题,欢迎与其他 AMP 用户取得联系,讨论您的具体用例。

前往 Stack Overflow

AMP 项目强烈鼓励您参与并做出贡献!我们希望您能成为我们开放源代码社区的持续参与者,但我们也欢迎您对所热衷问题做出一次性贡献。

编辑 GitHub 上的示例