Sagar Jajoriya
Sagar Jajoriya

Reputation: 2375

Best way to dynamic creation of file input

I have some custom upload file options like multiple hyperlinks. When clicked on that, I need to trigger the hidden file input. Say, I have 10 hyperlinks to upload different icons.
There are two ways to do that:
1. Create 10 file inputs and hide them and manually trigger them when clicking on the respective hyperlink.
2. Create a common function for that when the user clicks on the hyperlink and in that function, create a file input using javascript and triggered it using js.

So, my question is that which one is best or there is an efficient way to do that.

Upvotes: 0

Views: 113

Answers (2)

A.J Alhorr
A.J Alhorr

Reputation: 559

In javascript you can use the createElement function to create the input fields .createElement() then append those elements with .appendChild() to wherever you need.

So you can probably make a function to create the appropriate input field:

function appendInput(inputType){
    if(inputType==1){
      var input = document.createElement("input");
      input.setAttribute('type', 'file');
      $('body').appendChild(input);//just replace body with whatever element you want to append the input to e.g $('#someDivId').appendChild(input);
    }else if(inputType==2){
      //some other input
    }/...
  }

But if you simply trying to input different types of files, brk's answer is much more efficient

Hope that helps

EDIT Also having 10 different input fields that you hide and display would be somewhat bad from a maintenance perspective, so I would advocate creating different input fields depending on the hyperlink clicked.

EDIT2 from what I read you need each input to have a different name so you simply change the function to :

function(inputName){
    var input = document.createElement("input");
    input.setAttribute('type', 'file');
    input.setAttribute('name', inputName);//pass the name of each input field
    $('body').appendChild(input);
}

Upvotes: 0

brk
brk

Reputation: 50336

You can try by creating single input type='file' and limit the by accepted file types like this using accept attribute

<input type="file" id="profile_pic" name="profile_pic"
          accept=".jpg, .jpeg, .png">

Upvotes: 4

Related Questions