2

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; }
4
  • 1
    Most likely you are miss-diagnosing the problem. I see no id="upload" element, and i'm willing to bet it's the button. Clicking a button triggers the submit event, unless the button is specifically set as type="button". jsfiddle.net/Ebcu5/1 Commented Nov 26, 2013 at 22:15
  • Why you using regular JS and jQuery together like this? Would be much cleaner and simpler with just jQuery... Commented Nov 26, 2013 at 22:26
  • Sorry it was a copy&paste mistake... my button has the id="upload" as in the fiddle. Uploaded file. Commented Nov 26, 2013 at 22:29
  • Just because code is born in different times :) Commented Nov 26, 2013 at 22:30

2 Answers 2

4

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();
});
Sign up to request clarification or add additional context in comments.

2 Comments

or just make the button a button. type="button"
@KevinB type="button" fixed it for me. It makes sense. thank you
2

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.

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.