admin管理员组

文章数量:1353235

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.

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.

Share Improve this question edited Apr 3, 2018 at 11:03 Bourbia Brahim 14.7k4 gold badges43 silver badges54 bronze badges asked Mar 13, 2017 at 12:27 Carlos Vinicius F. GracioliCarlos Vinicius F. Gracioli 411 silver badge4 bronze badges 2
  • 1 Use this: input.setAttribute('multiple',''); – behzad besharati Commented Mar 13, 2017 at 12:30
  • That's what I was looking for, thank you @behzadbesharati – Carlos Vinicius F. Gracioli Commented Mar 13, 2017 at 12:42
Add a ment  | 

3 Answers 3

Reset to default 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);

input.setAttribute('multiple','');

Solved the problem.

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.

本文标签: javascriptHow to add quotmultiplequot attribute to dynamic generated Input FileStack Overflow