coderex
coderex

Reputation: 27855

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

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?

Upvotes: 46

Views: 65013

Answers (6)

mehdi
mehdi

Reputation: 11

This tested code helps you:

$("body").on('change', 'input#fileid',function(){
    alert($(this).val());});

Upvotes: 1

user1899563
user1899563

Reputation:

<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>

Upvotes: 12

Adi Prasetyo
Adi Prasetyo

Reputation: 1050

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'.

Upvotes: 0

Eng Cy
Eng Cy

Reputation: 1557

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


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

Upvotes: 11

marimaf
marimaf

Reputation: 5410

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

Upvotes: 0

mike clagg
mike clagg

Reputation: 840


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

Upvotes: 38

Related Questions