0

i have a form , there is an input type file , that element has a button with a on click event calling a function to upload the file (image), after that user has filled all his data hit the button validate , i want to clear the input type file once the user has clicked upload file and file has been uploaded , because what happening is that file to be uploaded to the server it takes time when the user hit upload file and also when he clicks validate button because it's passing in http request as an element of the form so what i want is to remove the file from the input once it is uploaded , this is my code i tested different scenarios none of them has worked.

<div>
    <input type='file' name='img1' id='img1'>
    <input type="button" value="upload" onclick="uploadFile()">
  <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
</div>

js

function _(el){
    return document.getElementById(el);

}
function uploadFile(){
    var file = _("img1").files[0];
    var e = document.getElementById("img1");
    var formdata = new FormData();
    formdata.append("img1", file);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler, false);
    ajax.open("POST", 'distination');
    ajax.send(formdata);
    formdata.delete("img1");
    formdata = '';
    _("img1").files[0] = '';

    e.value ='';
    $('#img1').val('');
    $('#img1')[0].reset();
}

the action of the form is PHP_SELF

Guns_Roses
  • 165
  • 2
  • 11

1 Answers1

1

I found this by searching StackOverflow for what you are specifically trying to do:

function resetForm($form) {
    $form.find('input:file').val('');
}
// to call, use:
resetForm($('#myform'));

This solution was derived entirely from Resetting a multi-stage form with jQuery

Example usage when you submit the form would be:

$('#validateButton').click(function (e) {
    e.preventDefault();
    resetForm($('#myform'));
    $('#myform').submit();
});

Where #validateButton and #myform should be replaced with the actual names of your DOM elements.

Community
  • 1
  • 1
Alexander Dixon
  • 837
  • 1
  • 9
  • 24