Search code examples
javascripthtmlcssfrontendamp-html

With AMP HTML, is it possible to get ID or other properties from clicked element, append them and create URL for an anchor tag?


I have a set of check input. Each one contains a unique ID. On checking box (on click) I want to get this ID and create a string of type '/some/path/?myids=checkOne,checkTwo (where checkOne and checkTwo are IDs of two different check input that have been clicked.

I understand that I can use state management - but my issue is: how can I limit how many checkboxes to create custom string for? For example, I want to have a limit of 5 comma separated IDs. Since AMP logic is limited I am not sure how to do complex logic with it.

Here are the steps:

  1. show set of checkboxes.
  2. user can click any of these checkboxes
  3. as user clicks on a checkbox, an achor tag href=... needs to be updated by appending the substring ?myids=checkOne.
  4. if user clicks on another checkbox then the href tag needs to be updated to this: ?myids=checkOne,checkTwo and so on until at the most 5 checkboxes are clicked.

Is this at all possible? Thanks

Documentation is not very clear on how to approx complex logic and not much found on searching.


Solution

  • One option is to use amp-selector and then limit the number of selected items when binding using .slice():

    <amp-state id="selected">
      <script type="application/json">[]</script>
    </amp-state>
    
    <amp-selector layout="container" multiple on="select:AMP.setState({selected: event.selectedOptions})">
      <div option="1">First</div>
      <div option="2">Second</div>
      <div option="3">Third</div>
    </amp-selector>
    
    <div hidden [hidden]="selected.length < 3">You can only select two options.</div>
    <a href="/?ids=" [href]="'/?ids=' + selected.slice(0, 2)">Click me</a>
    

    This limits the number of selected IDs to two and displays a warning if the user selected all three.