Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 969
Ashish Avatar asked May 24 '26 00:05

Ashish


1 Answers

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];
}
like image 87
Sushanth -- Avatar answered May 25 '26 12:05

Sushanth --