I’m trying to design a custom input using the label tag and hiding the actual input but it seems it is not possible to use a button element for this purpose (Upload dialog won’t open when I click on the button I use the below code and both the input and button are inside the label element.
There is a change event listener listening on the input element
Is there a technical issue with using button for this purpose ?
<label class="label" data-toggle="tooltip" title="Change your avatar">
<button type="button" id="avatar" class="btn btn-outline-warning">Upload Photo</button>
<input type="file" id="input" name="image" accept="image/*" hidden />
</label>
I tried h3 or even img elements instead of button with this same code and they work.
only problem is with button element.
>Solution :
Your HTML is invalid. A label can only be associated with one form control.
After error recovery is applied, clicking on the label will trigger the first form control inside it. That is the <button>
not the <input>
.
- Remove the button.
- Apply any CSS you want to the label itself
- Add
tabindex
to the label so it can be selected without a mouse/trackpad/etc - Add a
keypress
event listener so the file input can be triggered without a mouse/trackpad/etc
document.querySelector('label').addEventListener('keypress', (event) => {
if (["Enter", " "].includes(event.key)) {
event.target.querySelector('input').click();
} else console.log(event.key);
});
<label class="label" data-toggle="tooltip" title="Change your avatar" tabindex="0">
Upload Photo
<input type="file" id="input" name="image" accept="image/*" hidden />
</label>