0

$('.this_add').click(function(){
 $('.add_upload').append('<input type="file" name="file[]">');
 $('input[type="file"]:last').click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
   <body>
      <button class="this_add">add</button>
      <form action="" method="POST" enctype="multipart/form-data">
         <input type="file" name="image[]" />
         <div class="add_upload"></div>
         <input type="submit"/>
      </form>
      
   </body>
</html>

I have a scenario like the above snippet. If the user click add button then it will append an input type file into a <div class="add_upload> then trigger a click event on it and if the the user click cancel or close like this below image then the input type file will be remove. enter image description here

I want to ask, is it possible to check click event on "cancel or close" on input type file in html with jQuery or Javascript ?

Reynald Henryleo
  • 397
  • 2
  • 7
  • 22
  • 1
    Possible duplicate of [How to detect when cancel is clicked on file input?](https://stackoverflow.com/questions/4628544/how-to-detect-when-cancel-is-clicked-on-file-input) – nem035 Jun 20 '17 at 03:07

2 Answers2

0
   var file = document.getElementById('file')

    file.onclick = charge

    function charge()
    {
        document.body.onfocus = roar
        console.log('chargin')
    }

    function roar()
    {
        if(file.value.length) alert('ROAR! FILES!')
        else alert('*empty wheeze*')
        document.body.onfocus = null
        console.log('depleted')
     }


    $(input[type="submit"]).click(function(){
        document.getElementById("file").click()
    })

Hope it help!

0

In your $('.this_add').click(function(){" you should set a flag (in my case I set window.inputFileTrueClosed = true) so you can detect when the window gets the focus after pressing the button "Cancel" for that type of event. The following detect if the window gets the focus again: it means that "Cancel" button could have been pressed:

var isChrome = !!window.chrome;

    window.addEventListener('focus', function (e) {
       
    
    if(window.inputFileTrueClosed != false){
      
        if(isChrome == true){
           setTimeout(
                    function() 
                    {
                         if(window.inputFileTrueClosed != false){
   //if it is Chrome we have to wait because file.change(function(){... comes after "the window gets the focus"
                         window.inputFileTrueClosed = false; 
                         }
                    }, 1000);
}
else
{
        // if it is NOT Chrome (ex.Safari) do something when the "cancel" button is pressed.

        window.inputFileTrueClosed = false;
        
    }
}
})

Obviously the window gets the focus for many other events BUT with the flag you can select the one you need to detect.

giuseppe
  • 105
  • 9