Search code examples
formsamp-html

Dynamic AMP Selector


How can I change dynamically where it says 40,95€/mes to the option selected in the radio buttons using AMP?

<form id="myform" method="get" action-xhr="#" target="_top">
  <amp-selector class="radio-selector" layout="container" name="my-selector">
   <div class="background_gris_0" option="b">
      <label>
         <div class="clm1 left center_input">  
            <input name="answer1"
               value="Value 1"
               type="radio"
               on="change:myform.submit">
         </div>
         <div class="clm8 left">Antes 10GB* / AHORA 20GB / Llamadas  ilimitadas / 19,95€/mes</div>
      </label>
   </div>
   <div class="background_gris_1" option="c">
      <label>
         <div class="clm1 left center_input"><input name="answer1"
            value="Value 2"
            type="radio"
            on="change:myform.submit"></div>
         <div class="clm8 left">Antes 20GB* / AHORA 50GB / Llamadas  ilimitadas / 24,95€/mes</div>
      </label>
   </div>
  </amp-selector>
</form>

<div class="center">
  <h1> 40,95€/mes</h1>
</div>

JS Fiddle


Solution

  • This can be achieved by using the amp-bind component. First of all, I would like to suggest you to remove all change events from radio buttons in amp-selector. Shift that 'myForm.submit' action to amp-select's 'select' event.

    Create a state variable called 'currentPrice'. This will be null in the beginning. But when a radio input is selected, this will have a value and update the text in the h1 element.

    So, in radio buttons add this (change the value of currentPrice accordingly):

    on="tap:AMP.setState({currentPrice: '19,95€/mes'})"
    

    Then, in the h1 element do this:

    [text]="currentPrice"
    

    So whenever the radio button is tapped, the text at the bottom will be updated with price.

    You can see the jsfiddle here:

    Js Fiddle

    I have removed form submit event for simplicity.