3

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>

2 Answers 2

3

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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

I need to use different ID with my file handler
0
//variable = id of an element.
function cropper(variable){
     var selectedImg = $('#'+variable)[0].files[0];
}

Comments

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.