Grand Marshal Braev
Grand Marshal Braev

Reputation: 283

Counterpart of this script in jQuery

I have an html, when input has been changed, will call a javascript function:

<input type="file" id="file-uploaded" onchange="checkinput(this);">

And the script will read if the input really contains a file:

function checkinput(input) {
    if (input.files && input.files[0]) {
        // do something...

Then, when I try it in jQuery:

$(document).on("change", "#file-uploaded", function(){
    if ($(this).files && $(this).files[0]) {
        // do something...
    }
});

it does not work. What is the right counterpart of the first script when converting it to jQuery?

Upvotes: 0

Views: 81

Answers (2)

TeaCoder
TeaCoder

Reputation: 1977

Try something like below:

   $("#file-uploaded").on("change", function(){
        if ($(this).files && $(this).files[0]) {
            // do something...
        }
    });

Upvotes: 0

Robin Carlo Catacutan
Robin Carlo Catacutan

Reputation: 13699

You are close. Change this : $(this).files to this: $(this)[0].files

Your Jquery code now will look like this:

$(document).on("change", "#file-uploaded", function(){
    if ($(this)[0].files && $(this)[0].files[0]) {
        // do something...
    }
});

Upvotes: 2

Related Questions