5

I have a hidden file upload as it looks really bad, I have displayed a nicer looking button and would like it to click the hidden file upload when its clicked.

function ClickUpload() {
    $("#FileUpload").trigger('click');
}

<div id="MyUpload">
    <span id="FileName">Choose File</span>
    <input id="uploadButton" type="button" value="Upload" onclick="ClickUpload()"> 
</div>
<div id="hideUglyUpload">
    <input type="file" name="FileUpload" id="FileUpload"/>
</div>

So far i can move into the function ClickUpload() but it just passes through the click without the file selection window popup.

6
  • 4
    it works for me jsfiddle.net/uAFY6/2 Commented May 12, 2014 at 15:04
  • 3
    Which browser are you using? Commented May 12, 2014 at 15:05
  • 1
    The only thing I can think of is on the same line as @A.Wolff 's comment... Perhaps some browsers will only initiate the file dialog when it is triggered by a user initiated event. Your trigger function is not user initiated so the browser might be blocking it. Commented May 12, 2014 at 15:07
  • @Lix AFAIK, older browser (chrome version?) doesn't allow it on hidden input, input needs to be put outside viewport. But as i can test it, now it works on chrome Commented May 12, 2014 at 15:09
  • 1
    When using .triggerhandler() you can check weather the click was triggered and if not, to display a normal input type=file: api.jquery.com/triggerhandler Commented May 12, 2014 at 15:13

2 Answers 2

5

I prefer not to have inline JS function calls in markup ... so a little change...

   $(document).ready(function() {
      $('#uploadButton').on('click',function(evt){
         evt.preventDefault();
         $('#FileUpload').trigger('click');
     });
  });

<div id="MyUpload">
    <span id="FileName">Choose File</span>
    <input id="uploadButton" type="button" value="Upload"> 
</div>
<div id="hideUglyUpload">
    <input type="file" name="FileUpload" id="FileUpload"/>
</div>
Sign up to request clarification or add additional context in comments.

Comments

4

Strange that it doesn't work. Try

<input id="uploadButton" type="button" value="Upload" onclick='$("#FileUpload").click()'> 

2 Comments

What's the difference between this and the OP's method?
I do the same code and write ajax method in the upload click.but here the function working two times.Have any solution?

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.