AMP: pre selected value in select box

1.1k Views Asked by At

What is the solution to have a pre selected value in the sample below? Let's say that the third option should be selected by default when data is retrieved from JSON and the select box is shown (without user interaction).

<script async src="https://cdn.ampproject.org/v0.js"></script>
<script async custom-element="amp-list" src="https://cdn.ampproject.org/v0/amp-list-0.1.js"></script>
<select>
<amp-list width="auto" height="100" layout="fixed-height" src="https://ampproject-b5f4c.firebaseapp.com/examples/data/amp-list-urls.json">
<template type="amp-mustache">
    <option value="{{url}}">{{title}}</option>
</template>
</amp-list>
</select>
2

There are 2 best solutions below

1
On

The simplest way is adding the selected attribute in the option tags to make it the default.

<option selected value="{{url}}">{{title}}</option>

If you want to explore other options, this SO post mentioned binding. amp-bind adds custom interactivity with data binding and expressions.

0
On

There is a solution with "mustache inverted sections", but it does not work in my case due to other factors involved.

I got it thanks to [Cathy Zhu][1], on [AMP Issues support page][2].

I will provide it, in case it would be helpful for someone:

<amp-selector>
<amp-list width="auto" height="200"
  layout="fixed-height"
  src="//amp-list-selector.glitch.me/api/amp-list-data.json">
  <template type="amp-mustache">
    {{#selected}}
    // content displayed if selected is true
    <div class="story-entry"  selected>
      <amp-img src="{{imageUrl}}" width="100" height="100"></amp-img>
    </div>
    {{/selected}}
    {{^selected}}
     // content displayed if selected is false
    <div class="story-entry">
      <amp-img src="{{imageUrl}}" width="100" height="100"></amp-img>
    </div>
    {{/selected}}
  </template>
</amp-list>

for the sample data:

{

"items": [ { "title": "Cat", "imageUrl": "https://lh3.googleusercontent.com/pSECrJ82R7-AqeBCOEPGPM9iG9OEIQ_QXcbubWIOdkY=w400-h300-no-n", "selected": true },

{
  "title": "Dog",
  "imageUrl": "https://lh3.googleusercontent.com/5rcQ32ml8E5ONp9f9-Rf78IofLb9QjS5_0mqsY1zEFc=w400-h300-no-n",
  "selected": false
},
{
  "title": "Mouse",
  "imageUrl": "https://lh3.googleusercontent.com/pSECrJ82R7-AqeBCOEPGPM9iG9OEIQ_QXcbubWIOdkY=w400-h300-no-n",
  "selected": false
},

{
  "title": "Fish",
  "imageUrl": "https://lh3.googleusercontent.com/5rcQ32ml8E5ONp9f9-Rf78IofLb9QjS5_0mqsY1zEFc=w400-h300-no-n",
  "selected": false
}

] }