3

I need to add multiple attribute to input type file but I don't know how to do it.

Below My code:

var input = document.createElement("input");
input.type = "file";
input.id = "files" + af;
input.name = "imgs[]";
input.className = "upload";

But I need the input to have multiple atribute.

2
  • 1
    Use this: input.setAttribute('multiple',''); Commented Mar 13, 2017 at 12:30
  • That's what I was looking for, thank you @behzadbesharati Commented Mar 13, 2017 at 12:42

3 Answers 3

8

Just use setAttribute() function like below example :

As ou can see you can create input that accepts only image :

 var af = 1;
var input = document.createElement("input");
  input.setAttribute("type","file");
  input.setAttribute("id" ,"files" + af);
  input.setAttribute("name","imgs[]");
  input.setAttribute("multiple","");
  input.setAttribute("accept","image/*");
 
  input.className = "upload";
     
document.body.appendChild(input);     
  console.log(input);

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for answering. With your code I get the same result " <input type="file" id="files1" name="imgs[]" class="upload"> " but I need something like this " <input type="file" id="files1" name="imgs[]" class="upload" multiple> ". With the "multiple" attribute.
that's what I've mentiend in answer , you can do set all default attribu using this last
1
input.setAttribute('multiple','');

Solved the problem.

Comments

0

None of the answers fully explain this, though they are somewhat correct. The problem is that the 'multiple' attribute must be set AFTER adding the element to the DOM. I'm not sure why it works this way, but I could not get this to work until I changed the order of execution. Here is how it should look:

const fileElement = document.createElement("input");
fileElement.type = 'file';
document.body.appendChild(fileElement);
fileElement.setAttribute('multiple', '');

In my case, I have made this element hidden (with additional code), so I just attached it to the body. You'll want to attach it to a parent element that makes more sense if you are displaying this element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.