Home » Html » How do I call a JavaScript function after selecting a file from the Select File window and closing it?

How do I call a JavaScript function after selecting a file from the Select File window and closing it?

Posted by: admin November 29, 2017 Leave a comment

Questions:

I have a file input element

<input type="file" id="fileid">

How do I call a JavaScript function after selecting a file from the dialog window and closing it?

Answers:

jQuery("input#fileid").change(function () {
    alert(jQuery(this).val())
});

Questions:
Answers:
<input type="file" id="fileid" >

the change will function when you put script below the input

<script type="text/javascript">
$(document).ready(function(){
    $("#fileid").on('change',function(){
        //do whatever you want
    });
});
</script>

Questions:
Answers:
<script>
       function example(){
               alert('success');
       }
</script>


<input type="file" id="field" onchange="example()" >

Questions:
Answers:

Try declaring on the top of your file:

<script type="text/javascript">
  // this allows jquery to be called along with scriptaculous and YUI without any conflicts
  // the only difference is all jquery functions should be called with $jQ instead of $
  // e.g. $jQ('#div_id').stuff instead of $('#div_id').stuff
  $jQ = jQuery.noConflict();
</script>

then:

<script language="javascript">   
$jQ(document).ready(function (){
    jQuery("input#fileid").change(function () {
        alert(jQuery(this).val());
    });
});

(you can put both in the same <script> tag, but you could just declare the first part in you parent layout for example, and use $jQ whenever you use jQuery in you child layouts, very useful when working with RoR for example)

as mentioned in the comments in another answer, this will fire only AFTER you select a file and click open. If you just click “Choose file” and don’t select anything it won’t work

Questions:
Answers:

I think your purpose is achievable, but AFAIK no such event like that.

But to achieve that you need cooperate with 3 event,
i assume you just need to know about the file name.
I created walk around here

  1. Firstly the change event just fired when actual change happen, selecting same file won’t trigger change event so do opening dialog and cancel it.
  2. Then clicking choose file the input element will gain focus, when pop up file dialog opened input element losing the focus.
  3. When pop up file dialog closed, input element will regaining it focus.
  4. So you might run client side validation on client side when the input element losing it focus ‘again’.