Marco Marsala
Marco Marsala

Reputation: 2462

Why triggering a click event on a file input will trigger also submit event on form?

I'm skinning a file input in an HTML form. I achieved the result by hiding the input, then I designed my own button and onclick on that button, I trigger the click event on the hidden input, to open the native browse window. This works, but when I close the browse window, the Javascript submit handler is triggered on form (but no submit really happen, only the event is triggered).

I prepared a fiddle: http://jsfiddle.net/Ebcu5/

HTML:

<form id="form">
    <input id="file" type="file" name="photo" />
    <button id="upload">Browse</button>
</form>

JS:

$("#form").submit(function(){
    alert('submit event triggered');
});

document.getElementById('upload').addEventListener('click',function(){
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("click", true, true);
    uploading = true;
    document.getElementById('file').dispatchEvent(evt);
});

CSS:

input#file { position: fixed; top: -100px; }
button { border: solid 3px black; border-radius: 3px; font-size: 18px; line-height: 20px; text-transform: uppercase; font-family: Arial; line-height: 31px; background: #fd6706; border-radius: 13px; }

Upvotes: 2

Views: 9633

Answers (2)

ThinkingCap
ThinkingCap

Reputation: 213

Change: <button id="upload">Browse</button>

To: <button id="upload" type="button">Browse</button>

Credit for this goes to Kevin B for his comment on another answer:

or just make the button a button. type="button" – Kevin B Nov 26 '13 at 22:35

Just wanted it to be an actual answer so people would see it without digging thru the comments.

Upvotes: 2

Marco Marsala
Marco Marsala

Reputation: 2462

Solved. Just use a evt.preventDefault() in the upload click event handler.

Updated fiddle: http://jsfiddle.net/Ebcu5/2/

document.getElementById('upload').addEventListener('click',function(evt){
                evt.preventDefault();
    document.getElementById('file').click();
});

Upvotes: 4

Related Questions