Reputation: 27855
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
Reputation: 11
This tested code helps you:
$("body").on('change', 'input#fileid',function(){
alert($(this).val());});
Upvotes: 1
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
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
Upvotes: 0
Reputation: 1557
<script>
function example(){
alert('success');
}
</script>
<input type="file" id="field" onchange="example()" >
Upvotes: 11
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
Reputation: 840
jQuery("input#fileid").change(function () {
alert(jQuery(this).val())
});
Upvotes: 38