1

I have a hidden input[type=file] and a separate button which triggers click on this hidden input. How can I detect the value change in this hidden input, i.e, when the user has selected a file?

<form id="photo_upload_form" method="POST" enctype="multipart/form-data">
    <button >Upload a Photo</button>
    <input name="file" type="file" hidden />
</form>

Javascript:

$('#photo_upload_form button').click(function(){
        $('input[type="file"]').trigger('click');
});
$('input[type="file"]').change(function(){
    alert('Change !');
});

EDIT: My button click submits the form so I had to use a preventDefault !

6
  • You can use a mutation observer Commented Dec 15, 2014 at 2:42
  • Is there a simple solution for it? If somehow I can trigger change? Commented Dec 15, 2014 at 2:48
  • Can you show us/explain to us what you have tried so far to achieve what you are wanting? Commented Dec 15, 2014 at 2:51
  • 1
    I just used the .change() function. Everything works fine if I dont hide the input field ! Once I do, it doesn't work. Commented Dec 15, 2014 at 2:52
  • jsfiddle.net/arunpjohny/c5e836gn/2 - seems fine Commented Dec 15, 2014 at 3:12

2 Answers 2

3

using onchange for input[type=“file”]

<input type="file" onchange="myFunction()">

here is demo http://jsfiddle.net/qs4y0rLe/

as your code, change like below

 $('input[type="file"]').on('change',function(){
            alert('Change !');
    });

about jquery .on(), attach an event handler function for one or more events to the selected elements. more --> http://api.jquery.com/on/

http://jsfiddle.net/qs4y0rLe/1/

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

6 Comments

It is a hidden input field, so the change doesn't automatically trigger, right?
@user3142839 what you mean hidden input[type=file]?? display:none; or type="hidden" ?
<input type="file" hidden> or display: none for that matter
@user3142839 i upgraded my answer, check it
@user3142839 upgraded my answer
|
0

It will still trigger change event on the input[type=file], sth like

$("input[type=file]").on('change',function() {});

1 Comment

@user3142839 what about visibility: hidden

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.