Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Making a custom HTML input element with a button element

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading