Conditionally hide or show inputs - AMP

淺唱寂寞╮ 提交于 2020-07-18 05:11:00

问题


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!


回答1:


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>


来源:https://stackoverflow.com/questions/45169583/conditionally-hide-or-show-inputs-amp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!