简体   繁体   中英

Displaying images from file inputs in Javascript

I need to run a function when someone has finished selecting a file using the file input service. By "file input service", I mean:

<input type="file" name = "foo" id="foo">

I have tried to do this in various ways, first by creating a form to do so and using other techniques, but nothing seems to work. There are several ways to detect if the thing has something, like by using:

document.getElementById("foo").files[0]

This only returns a value if you run it, but I cannot constantly compile a while statement to do this.

Pure Javascript

You can use pure javascript like below. This code basically uses document.getElementById() to get the input element, and .addEventListener() and change to do something when the input field is changed.

 document.getElementById("foo").addEventListener("change", function() { console.log("Changed"); }); 
 <input type="file" name="foo" id="foo"> 

jQuery

Use jQuery .change() . Basically, this code will console.log "Changed" when the input changes (you add a file).

 $("#foo").change(function() { console.log("Changed"); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="file" name="foo" id="foo"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM