2

i used change event of jQuery for capturing selecting image from my computer.

$("#user_photo").change(function () {
  alert('yes');
}); 

But my problem is when i select same file again then this function does not work. yes obvious it won't. but i want a solution of this. can you help me?

Manish Prajapati
  • 1,583
  • 2
  • 13
  • 21

2 Answers2

2

This behavior is not the same on all browsers. For example with the following code snippet on firefox, you'll have the alert even if you select the same file.

$('#test').on('change', function() {
  alert('yes');  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="test" type="file" />

But you can be tricky. You can use an input file and when a file is uploaded, take it on your server, destroy the input file and recreate a new input file. But if you want to do that, you'll have to decide how to upload the file on your server because not every browser have the javascript FileAPI. Here an example :

$(document.body).on('change', '#test', function() {
  // Upload the file on your servlet, i can't really do the code for that. You case use the FileAPI or a library for that. Just take care of browsers compatibility : http://caniuse.com/#feat=fileapi
  
  // When the file is uploaded
  alert('yes');
  
  // Replace the input by a new one
  $(this).replaceWith('<input id="test" type="file">');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="test" type="file" />

Of course you can improve this code by displaying the uploaded file.

Magus
  • 14,796
  • 3
  • 36
  • 51
  • Actually i am opening a modal when user select an image then can crop it. if user click on in model but if user wants to again think and want to crop different axis then problem caused. i hope you understand that. – Manish Prajapati Oct 01 '15 at 07:21
  • @ArP: You can apply the technique above to that scenario. – T.J. Crowder Oct 01 '15 at 07:46
-2

Use on event, like this

$("#user_photo").on("change", function () {
  alert('yes');
}); 

or if the element is dynamically added, following can be used

$("body").on("change", "#user_photo", function () {
   alert('yes');
});
Ravneet
  • 300
  • 1
  • 5