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.

6
  • You're getting an error, don't you? Also, your code does not try to show an input, it only creates one. Commented May 17, 2012 at 21:51
  • You are also not able to click a file input using jquery; it's not possible for security reasons. Commented May 17, 2012 at 22:11
  • @Daedalus -- input.click(); will execute a click event on the DOM element 'input' Commented Dec 7, 2016 at 16:45
  • @user1789573 Have you successfully done that in Firefox? Commented Dec 7, 2016 at 23:49
  • @user1789573 Obviously, given this question is 4 years old, it helps to do your research first. In short: it didn't work at one point; now it does. Commented Dec 7, 2016 at 23:57

1 Answer 1

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/

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

6 Comments

thank you Marc, but I don't want to show this element in front, how this can be done?
@PandaYang, Add CSS to hide it: input {display: none}, and when that works for you, feel free to approve this solution.
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.
@PandaYang, it works just fine for me using Firefox on Windows. See here: jsfiddle.net/JQHPV/4
document.body.appendChild(input) will add the element to the DOM. You can even uniquely identify it through its properties (i.e. tagName = "MyUniqueInputTagName");
|

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.