0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.