bool3max
bool3max

Reputation: 2865

How to prevent form submit when choosing a file with <input type="file>?

I have a file input on my page:

<input type="file" id="file-main" style="display:none;" name="file-main">

And I have a lable pointing to that input:

<button class="main-button" id="file-choose-btn"><lable for="file-main">Choose Image</lable></button>

But when I press the button (to choose the file), the form immediately gets submitted, and tries to execute the PHP file (that's in the form's "action"). I do not yet have that file, so it returns a HTTP 404 error.

Basically, my question is, how do I prevent the form from being executed after clicking the (or a button in this case).

I've tried using an event handler that prevents the default action of the event:

document.getElementById("file-choose-btn").onclick = function(e){
            e.preventDefault();
}

But then I cannot even choose the file, since the window doesn't even open.

Any solutions? Thanks.

Upvotes: 2

Views: 3387

Answers (1)

dfsq
dfsq

Reputation: 193261

Make button type button so it will not submit a form:

<button type="button" class="main-button" id="file-choose-btn">
    <lable for="file-main">Choose Image</lable>
</button>

By default button has type submit so hence the behaviour you get.

Upvotes: 15

Related Questions