1

I am using the following jsfiddle code to determine uploaded image file's attributes. There are multiple file upload elements. I wish to know the current id of the element that has called the function so that I can use switch function. For example, if id = file1, then do this, elsif it is file2, then do this and so on. I used $(this).attr("id"), this.id; but none works.

$(window).load(function(){
    var _URL = window.URL || window.webkitURL;
    function displayPreview(files) {
        var reader = new FileReader();
        var img = new Image();
        reader.onload = function (e) {
            img.src = e.target.result;
            fileSize = Math.round(files.size / 1024);
            img.onload = function () {
                $('#preview').append('<img src="' + img.src + '">');
            }
        };
    reader.readAsDataURL(files);
    }
    $("#file1").change(function() {
        var file = this.files[0];
        displayPreview(file);
    });
    $("#file2").change(function() {
        var file = this.files[0];
        displayPreview(file);
    });
    $("#file3").change(function() {
        var file = this.files[0];
        displayPreview(file);
    });
});

This is the html code:

<input type="file" id="file1" /></br>
<input type="file" id="file2" /></br>
<input type="file" id="file3" /></br>
<div id="preview"></div>

So, how do I know the id of the current element which has called the function?

1 Answer 1

2

You can capture the id of the element inside of your event handlers by using the event target

$("#file3").change(function(e) {
    var id = e.target.id;
    var file = this.files[0];
    displayPreview(file, id);
});

You will need to pass in "e" as the event in your anonymous function.

Alternatively, you can use a jQuery selector on this

var id = $(this).attr("id");

Once you have the id, pass it into your method.

displayPreview(file, id);
Sign up to request clarification or add additional context in comments.

2 Comments

That did not work, however, that gave me an idea to make it workable. I did the following, and it worked for me. $("#file3").change(function() { var id = $(this).attr("id"); var file = this.files[0]; displayPreview(file,id); });
@sridhar I'd be interested to know why it didn't work. But yes, that's an alternative. I'll update my answer to reflect it.

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.