2

I am trying to create a keyboard accessible upload page using angular 2. I am having trouble to enable "Choose a file to upload" using space bar and enter keys. I am able to upload files by clicking the label.

<label for="files" > Choose a file to upload </label>
<input type="file" id="files" (click)="upload($event)"/>

The display of input is none and I am using the label to allow users to choose which file to upload. I tried onkeypress, keyup and keydown but I am not able to make it keyboard accessible for the label.

Matt-pow
  • 946
  • 4
  • 18
  • 31
  • Seems to work fine in https://plnkr.co/edit/UKuSKU5hg9bhakEHR32Y?p=preview with tab and space. – Günter Zöchbauer Mar 07 '17 at 07:21
  • No. Because I am hiding the default choose file using display:none. I just want users to see Choose a file to upload label. – Matt-pow Mar 07 '17 at 07:22
  • How do you expect a useful answer if you omit essential parts of your question. Please provide the code that allows to reproduce your problem and explain the expected behavior. – Günter Zöchbauer Mar 07 '17 at 07:26
  • I indicated "The display of input is none". – Matt-pow Mar 07 '17 at 16:31
  • That's quite hard to interpret without seeing code. – Günter Zöchbauer Mar 07 '17 at 16:32
  • Basically I am trying to use a button to replace type="file". I just find out I couldn't use label because it doesn't have the functionality as a button. I want to be able to choose a file by just using the keyboard, but not clicking. ` ` `input {display:none}` @GünterZöchbauer – Matt-pow Mar 08 '17 at 08:08

1 Answers1

2

I had the same problem; I just added a keypress handler to the label to trigger a click on it if the space or enter key is pressed.

Here's a working Plunkr.

HTML (don't forget the tabindex="0"):

<label class="btn" for="files" tabindex="0" (keypress)="onUploadLabelClick($event)">Choose a file to upload</label>
<input class="hiddenFileUpload" type="file" id="files" (click)="upload($event)"/>

Relevant function:

onUploadLabelClick(evt): void {
    var keyCode = evt.which || evt.keyCode;
    if (keyCode === 13 || keyCode === 32) {
        $(evt.target).click();
        evt.preventDefault();
    }
}

I use JQuery here, but it's simple enough to do the same with pure JS obviously.

melanie johnson
  • 597
  • 3
  • 16