I have a file input element
How do I call a JavaScript function after selecting a file from the d
<script>
function example(){
alert('success');
}
</script>
<input type="file" id="field" onchange="example()" >
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
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
<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());});
jQuery("input#fileid").change(function () {
alert(jQuery(this).val())
});