Ashish
Ashish

Reputation: 14707

How to pass file element in JavaScript function

I am using JavaScript in my application in a function name cropper like that

function cropper(){
var selectedImg = $('#image_file')[0].files[0];
}

I am calling it using file element with ID image_file from my html like this

 <input type="file" id="image_file" name="picture1" onchange="cropper()"/><br>

All I want to change the above function like

function cropper(variable){
var selectedImg = variable[0].files[0];
}

so that I can assign different ID for different file element. Could you please suggest me how can I achieve the above functionality.

Edit:

I have 4 file attachment button in my website and I wants to use different ID for that so it would be like that.

<input type="file" id="picture1" name="picture1" onchange="cropper(picture1)"/><br>
<input type="file" id="picture2" name="picture2" onchange="cropper(picture2)"/><br>
<input type="file" id="picture3" name="picture3" onchange="cropper(picture3)"/><br>
<input type="file" id="picture4" name="picture4" onchange="cropper(picture4)"/><br>

Upvotes: 3

Views: 7526

Answers (2)

Ecropolis
Ecropolis

Reputation: 2025

//variable = id of an element.
function cropper(variable){
     var selectedImg = $('#'+variable)[0].files[0];
}

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

You can pass the event object to the handler

<input type="file" id="image_file" name="picture1" 
                                   onchange="cropper(event)"/><br>

Then use the event object in the method

function cropper(event){
   var selectedImg = event.target.files ? event.target.files[0]
                                        : $('#image_file')[0].files[0];
}

Upvotes: 3

Related Questions