Clive Stewart
Clive Stewart

Reputation: 31

How to upload a file and submit the form in one action

Here is the code I have so far:

<form method="POST" id="frmProduct" name="frmProduct" action="" enctype="multipart/form-data">    
    <a onclick="uploadAvatar();" href="#"> <img src"path-to-image"/> </a>
    <input type="file" name="mediafile" id="mediafile" style="display: none;">
</form>
function uploadAvatar() {
    let element = document.getElementById('mediafile');
    let form = document.getElementById('frmProduct');

    element.click();

    element.onchange = function() {                         
        form.submit();
    }
}

Can this be written more elegantly using vanilla JS?

Upvotes: 0

Views: 140

Answers (1)

Deadron
Deadron

Reputation: 5289

You don't need to use Javascript. Just use a button with type submit. I would consider it a bad practice to auto submit a page without user confirming the selection. When this is done in other places, data is submitted via ajax to avoid a page load.

Upvotes: 2

Related Questions