1

I would like raise the onchange event of the input file type by clicking a button:

Example:

<input id="File1" type="file" onchange="show(this)"  />
<input id="Button1" type="button" value="button" onclick="butclick()" />
<input id="Button2" type="button" value="button" onclick="document.getElementById('File1').onchange()" />
<input id="Button3" type="button" value="button" onclick="document.getElementById('Button1').onclick()" />

<script>
function butclick() {
    alert('yes');
}
</script>

I can trigger the click event of another button but not the onchange event of an input file.

1 Answer 1

5

I'd recommend to write all your Javascript code into the script tags to have everything on one place.

The "change" event is triggered, when the element (in you case input type file) changes and not by clicking another element

For example:

function handleFileInput() {
 console.log("change event of file input triggered.");   
}

document.getElementById("files").addEventListener("change", handleFileInput, true);

In this example the change event is attached to the file input and when the user chose a file the event is dispatched.

You can try the code on jsfiddle: http://jsfiddle.net/883LL/1/


But if you really want to dispatch the event by clicking a button you could try with dispatchEvent: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.dispatchEvent

Hope this helps!

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

2 Comments

+1 for using addEventListener instead of inline JS.
cant I trigger the change event thru a button or div click. Thats what I want to do. Thank you

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.