skip to Main Content

We have some HTML input checkboxes that are readonly as their checked state is controlled by another source, but the checkboxes can be tabbed into and toggled with pressing the space bar. This happens in all browsers except Safari as it wont let you tab into a readonly checkbox anyway.

How can I get this spacebar toggling disabled?

<input
  class="form-check-input"
  style="pointer-events: none;"
  type="checkbox"
  [(ngModel)]="registerAcceptTCs"
  id="acceptTCs"
  name="acceptTCs"
  required>

2

Answers


  1. Chosen as BEST ANSWER

    I found other pages on here that talk about affecting the spacebar functionality in both JavaScript and JQuery, but as this is in a registration form I didn't want any undesired effects caused by this.

    This was actually really easy to resolve in Angular, I just added a listener to the focus event on the input, and then call the blur() method which removes the focus so when the space bar is hit, it does not toggle checked state (it results in the browser functionality of scrolling down the page).

    <input
      class="form-check-input"
      style="pointer-events: none;"
      type="checkbox"
      [(ngModel)]="registerAcceptTCs"
      id="acceptTCs"
      name="acceptTCs"
      required
      (focus)="(iTC.blur())" //add this line
      #iTC> //add this line
    

  2. You need to add the attribute disabled to the element. This will disable user interaction with the checkbox. Add it like this:

    <input
      class="form-check-input"
      style="pointer-events: none;"
      type="checkbox"
      [(ngModel)]="registerAcceptTCs"
      id="acceptTCs"
      name="acceptTCs"
      required
      disabled> <!-- This is the new attribute -->
    

    By the way, I don’t think you need the style element anymore, but I’ll let you decide for your use case. 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search