Hide or show inputs conditionally - AMP

I am trying to create a form using Accelerated Mobile Pages (AMP) and I need to hide or show inputs based on user selection.

I have <select>

where users can select a country:

<select name="country" id="country" required>
    <option value="UK">United Kingdom</option>
    <option value="ES">Spain</option>
</select>

      

And if the user selects United Kingdom, I want to hide these inputs:

<input type="text" id="idcard" name="idcard">
<input type="text" id="mobile" name="mobile">

      

I've already tried using the "on" attribute inside the tag <option>

:

<option value="UK" on="tap:idcard.hide,mobile.hide">United Kingdom</option>

      

but it doesn't work and it is only valid in the tag <select>

, even the documentation says "All items".

I need to use tags <select>

and <option>

since there are many countries, not just 2, otherwise the "on" attribute will work with the radio input.

Is there any trigger or event I can use to hide or show the inputs based on the user's selection?

Hope someone can help! Thank!

+3


source to share


1 answer


You can use an event change

on an element select

and check the value that was selected and based on that value set the AMP state property visibility

to the value show

or hide

like this:

<select name="country" id="country" required
        on="change:AMP.setState({visibility: event.value=='ES'?'hide':'show'})">
 <option value="UK" >UK</option>
 <option value="ES" >Spain</option>
</select>

      

Then bind the class of the inputs to the visibility value:

<input type="text" id="idcard" name="idcard" 
       class="show"
       [class]="visibility||'show'">
<input type="text" id="mobile" name="mobile"
       class="show"
       [class]="visibility||'show'">

      



Then you just need a CSS class:

<style amp-custom>
  .hide {display: none;}
</style>

      

You will need to enable the amp-bind component:

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

      

+3


source







All Articles