10

I want to customize the file input button, so I use this code to create an file input element

function inputBtn(){
    var input=document.createElement('input');
    input.type="file";
    setTimeout(function(){
        $(input).click();
    },200);
}

<button id="ifile" onclick="inputBtn()">create</button>

However, when I click create, it shows nothing.

panda
  • 1,344
  • 3
  • 14
  • 35
  • You're getting an error, don't you? Also, your code does not try to *show* an input, it only *creates* one. – Bergi May 17 '12 at 21:51
  • You are also not able to click a file input using jquery; it's not possible for security reasons. – Daedalus May 17 '12 at 22:11
  • @Daedalus -- input.click(); will execute a click event on the DOM element 'input' – user1789573 Dec 07 '16 at 16:45
  • @user1789573 Have you successfully done that in Firefox? – Daedalus Dec 07 '16 at 23:49
  • @user1789573 Obviously, given this question is 4 years old, it [helps to do your research first](http://stackoverflow.com/questions/210643/in-javascript-can-i-make-a-click-event-fire-programmatically-for-a-file-input). In short: it didn't work at one point; now it does. – Daedalus Dec 07 '16 at 23:57
  • @Daedalus -- Ha! I didn't notice how old it was...good thing things have been updated, i'm glad! – user1789573 Dec 08 '16 at 15:19

1 Answers1

15

You're creating the new DOM element, but you're not attaching it to the DOM. You need something like:

document.getElementById('target_div').appendChild(input);

You can see how this works in a poorly done JSFiddle here: http://jsfiddle.net/JQHPV/2/

Marc
  • 11,403
  • 2
  • 35
  • 45
  • thank you Marc, but I don't want to show this element in front, how this can be done? – panda May 18 '12 at 10:21
  • @PandaYang, Add CSS to hide it: `input {display: none}`, and when that works for you, feel free to approve this solution. – Marc May 18 '12 at 15:02
  • I have tried the css, it won't work, because when the input button is hided, the window that it shows also be hided. I have tried another method, use the width and position to minimize the size of this input element and find a picture overlap it. also thank you for your help. – panda May 18 '12 at 17:23
  • @PandaYang, it works just fine for me using Firefox on Windows. See here: http://jsfiddle.net/JQHPV/4/ – Marc May 18 '12 at 17:29
  • document.body.appendChild(input) will add the element to the DOM. You can even uniquely identify it through its properties (i.e. tagName = "MyUniqueInputTagName"); – user1789573 Dec 07 '16 at 16:47
  • @panda you can also add hidden attribute. `input.hidden = true` – Johan Jun 30 '23 at 09:32