I am trying to build a form using Accelerated Mobile Pages (AMP) and I need to hide or show inputs based on user selection.
I have a <select>
where users can choose the country:
<select name="country" id="country" required>
<option value="UK">United Kingdom</option>
<option value="ES">Spain</option>
</select>
And if the user chooses United Kingdom I want to hide this inputs:
<input type="text" id="idcard" name="idcard">
<input type="text" id="mobile" name="mobile">
I have already tried using the "on" attribute inside the <option>
tag:
<option value="UK" on="tap:idcard.hide,mobile.hide">United Kingdom</option>
but it doesn't work and it is only valid on the <select>
tag even the documentation says "All elements".
I need to use <select>
and <option>
tags as there are a lot of countries and not just 2, otherwise with a radio input the "on" attribute would work.
Is there any kind of trigger or event I can use to hide or show inputs based on user selection?
Hope anyone can help! Thanks!
You can use the change
event on the select
element, and test the value that was selected, and based on that value, set an AMP state property visibility
to 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 value of visibility:
<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 CSS class:
<style amp-custom>
.hide {display: none;}
</style>
You will need to include amp-bind component:
<script async custom-element="amp-bind" src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With