Search code examples
amp-html

How to Increment Value in Input field with AMP?


I am trying to create a button in AMP that will increment the value in an input field. For example, what you would see in a quantity +- selector in an ecommerce product page.

I have tired looking at amp-bind, and amp-script, none of which seem to accomplish what I would consider so simple.

My AMP-HTML:

<button on="tap:AMP.setState({ value: value-1})">-</button>
<input name="qty" id="qty" type="number" min=1 [value]=1>
<button on="tap:AMP.setState({ value: value+1 })">+</button>

In normal javascript: it would be as simple as:

document.getElementById("qty").value++;

Any help is appreciated


Solution

  • Your current solution is really close. The only thing that is missing is updating the [value] binding on the input to use the AMP state variable that gets modified when the button is clicked. That will make the value dynamic based on the state variable.

    For clarity I renamed the amp-bind variable from you example to be currentValue

    <button on="tap:AMP.setState({ state: {currentValue: state.currentValue == 1 ? 1 : state.currentValue-1}})">-</button>
    <input name="qty" id="qty" type="number" min=1 value=1 [value]="state.currentValue">
    <button on="tap:AMP.setState({ state: {currentValue: state.currentValue+1 }})">+</button>
      
    <amp-state id="state">
      <script type="application/json">
        {"currentValue": 1}
      </script>
    </amp-state>
    

    Here is a full working example and the amp-bind documentation is a great resource as well.