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
&开发者_运维问答lt;input type="file" id="fileid">
How do I call a JavaScript function after selecting a file from the dialog window and closing it?
jQuery("input#fileid").change(function () {
alert(jQuery(this).val())
});
<script>
function example(){
alert('success');
}
</script>
<input type="file" id="field" onchange="example()" >
<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>
This tested code helps you:
$("body").on('change', 'input#fileid',function(){
alert($(this).val());});
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
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
- 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.
- Then clicking choose file the input element will gain focus, when pop up file dialog opened input element losing the focus.
- When pop up file dialog closed, input element will regaining it focus.
- So you might run client side validation on client side when the input element losing it focus 'again'.
精彩评论