javascriptangularcheckboxonclickevent-capturing

Angular click event: how to select a checkbox within an a element?


In my Angular app I have the following menu:

enter image description here

As you can see I have items (that are a elements) and a checkbox and a label in each of them:

<span class="caption">RAM</span>
<a class="item">
    <div class="item-checkbox">
        <input type="checkbox" tabindex="0" class="hidden">
        <label>4 GB</label>
    </div>
</a>
<a class="item">
    <div class="item-checkbox">
        <input type="checkbox" tabindex="0" class="hidden">
        <label>8 GB</label>
    </div>
</a>
<a class="item">
    <div class="item-checkbox">
        <input type="checkbox" tabindex="0" class="hidden">
        <label>16 GB</label>
    </div>
</a>

How should I add (click) to every item to correctly handle event capturing so if user click on label or on whole item I get the related checkbox selected?

...Or do you know a better way to reach what I mean?


Solution

  • To make sure that clicking on the label toggles the checkbox, include the input element inside of the label (as explained in MDN):

    <a class="sub-item item">
      <div class="item-checkbox">
        <label><input type="checkbox" tabindex="0" class="hidden">4 GB</label>
      </div>
    </a>
    

    If you also want the label to fill the anchor element, define the CSS as shown below. With this styling in place, clicking on the anchor will toggle the checkbox.

    .ui.secondary.menu a.item {
      padding: 0px;
    }
    
    div.item-checkbox {
      width: 100%;
      height: 100%;
    }
    
    div.item-checkbox > label {
      display: block;
      padding: .78571429em .92857143em;
    }
    
    div.item-checkbox > label > input {
      margin-right: 0.25rem;
    }
    

    See this stackblitz for a demo.