How to handle onchange event on input type=file in jQuery?

239,170

Solution 1

Demo : http://jsfiddle.net/NbGBj/

$("document").ready(function(){

    $("#upload").change(function() {
        alert('changed!');
    });
});

Solution 2

Or could be:

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

To be specific: $('input[type=file]#fileUpload1').change(...

Solution 3

It should work fine, are you wrapping the code in a $(document).ready() call? If not use that or use live i.e.

$('#fileupload1').live('change', function(){ 
    alert("hola");
});

Here is a jsFiddle of this working against jQuery 1.4.4

Solution 4

This jsfiddle works fine for me.

$(document).delegate(':file', 'change', function() {
    console.log(this);
});

Note: .delegate() is the fastest event-binding method for jQuery < 1.7: event-binding methods

Solution 5

Try to use this:

HTML:

<input ID="fileUpload1" runat="server" type="file">

JavaScript:

$("#fileUpload1").on('change',function() {
    alert('Works!!');
});

Share:
239,170

Related videos on Youtube

anmarti
Author by

anmarti

Full stack web developer using Microsoft .Net technologies. Over 8 years of web developing experience.

Updated on August 12, 2020

Comments

  • anmarti
    anmarti almost 4 years

    The code is:

    <input ID="fileUpload1" runat="server" type="file"
    

    The following works fine:

    <input onchange="javascript:alert('hola');" ID="fileUpload1"  runat="server" type="file"
    

    I'd like to get this result using jQuery, but that doesn't work:

    $('#fileUpload1').change(function (e) {
        alert("hola");
    });
    

    I am missing something? (Edit: Yes I missed include the *.js file.)

    • Esailija
      Esailija almost 12 years
      The id of the element is "fileUpload1" not "fileupload1". Are you also running your code after the element exists and you have included jQuery etc? Also check your browser console for javascript errors.
    • Michal Stefanow
      Michal Stefanow over 7 years
      I searched for similar keywords but I'm looking for "no jQuery" version...
  • Simon
    Simon almost 12 years
    live is deprecated, one should use on() nowadays
  • Chris
    Chris almost 12 years
    He is using v1.4.4 which doesnt support on()
  • Esailija
    Esailija almost 12 years
    live is deprecated for all jQuery versions, use .delegate
  • Arpit Srivastava
    Arpit Srivastava almost 12 years
    Sorry for I didn't see the problem properly...now check @Esailija