Setting the 'capture' attribute of an HTML Form Image Input via JavaScript

Viewed 375

For one of my projects I have a form containing file inputs (that accept .jpg and .png). I know that I can set the capture attribute in the input tag, so that when the button is clicked, instead of showing a file selector, it should directly go to the camera (aimed here at phone/tablet usage). This works well!

It would, for example, look like this:

<input type="file" accept="image/jpeg, image/png" capture>

Now I would like to dynamically add file inputs to the form with JavaScript, when they press a Add Another Image button.

I have gotten this far:

const input = document.createElement('input')
    
input.type = 'file';
input.name = 'image';
input.accept = 'image/jpeg, image/png';

document.getElementById('image-input-container').appendChild(input);
input.click();

Is there a way to set the capture attribute using JavaScript this way as well?

1 Answers

You can use setAttribute to set the capture.

input.setAttribute("capture", "");

The accept attribute should also be set to allow any type of image.

input.accept = 'image/*';
Related