oneday
oneday

Reputation: 1629

Triggering click on type=file with another button causes unexpected behaviour

I'm trying to create my own "upload" button instead of the default one. By clicking on my custom button I'm triggering a click on the original upload button:

HTML:

 <form id="myForm" enctype="multipart/form-data" action="api/upload.php" method="POST">
     <input type="hidden" name="MAX_FILE_SIZE" value="5120000" />
     <input name="userfile" type="file" class="choose-file"/>
     <button class="choose-picture"></button>
     <input type="submit" class="send-button" value='' />
 </form>

JS:

$('.choose-picture').click(function() {
    $('.choose-file').trigger('click');
});

I have another script that displays the picture that got uploaded when I click the submit button. If I use the original upload file button, nothing happens and that's ok (the picture is only suppose to show up after I choose and submit one), but when I click my custom (.choose-picture) button it acts as if I already chose a file for uploading, putting some mess in the img source and displaying a non-img (the icon you see when the source is wrong).

This is what the console says:

GET http://localhost/OrlenOla/%3Cbr%20/%3E%3Cb%3ENotice%3C/b%3E:%20%20Undefined…api/upload.php%3C/b%3E%20on%20line%20%3Cb%3E10%3C/b%3E%3Cbr%20/%3Euploads/ 403 (Forbidden) 

So it's acting as if I already called my upload script (which I have no intention to call at this stage as it's supposed to happen on submit).

Why is this happening? How can I fix it?

Upvotes: 1

Views: 427

Answers (2)

Anthony Grist
Anthony Grist

Reputation: 38345

If you don't explicitly specify a type attribute on a <button> element, it's treated as though you explicitly declared it as type="submit" (i.e. a button that's intended to submit the form):

submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
Source

That's why it's triggering your form submit event handler code, because it does submit the form.

Easiest way to fix this is to just specify type="button" on the element:

<button type="button" class="choose-picture"></button>

The other way (as you discovered) is to prevent the default behaviour of the button:

$('.choose-picture').click(function(e) {
    e.preventDefault();
    $('.choose-file').trigger('click');
});

Upvotes: 2

oneday
oneday

Reputation: 1629

I managed to resolve the issue:

$(document).ready(function() {
    $('.choose-picture').click(function(e) {
        e.preventDefault();
    $('.choose-file').trigger('click');
    });
});

Upvotes: 0

Related Questions