Dan
Dan

Reputation: 817

How do you set file input to nothing with JavaScript or HTML?

On the site I am developing, I have a file input that users can upload files from. It uses "Ajax" (not really) to send the file to a php file that is bound to an iframe. My question is that Firefox automatically fills in the file input element. Is there a way I can give users the option of clicking the submit button without sending the file? Or do I set the file value to null somehow and check for that in the php file? My code looks like this:

    Name: <input type='text' id='name'><br>
    Description: <textarea id='description' rows=10 columns=100></textarea><br>
    <form id="upload_form" method="post" enctype="multipart/form-data" action="uploadfile.php">
    <input type='hidden' value='' id='descriptionid' name='descriptionid'>
    <input type='file' name="file" id="file" size="27" value="">
    <input type='submit' value='Submit' onclick=';' id='submitPopup'>
    </form>

When the button is clicked it runs a JavaScript method and gets the values of name and description and also submits the input form. How do I let users have the option of uploading a file, and not have it auto filled in by their browser?

Upvotes: 1

Views: 6848

Answers (3)

cuixiping
cuixiping

Reputation: 25399

I answered this question in another topic: how to clear file input with javascript?

There's 3 ways to clear file input with javascript:

  1. set value property to empty or null.

    Works for IE11+ and other modern browsers.

  2. Create an new file input element and replace the old one.

    The disadvantage is you will lose event listeners and expando properties.

  3. Reset the owner form via form.reset() method.

    To avoid affecting other input elements in the same owner form, we can create an new empty form and append the file input element to this new form and reset it. This way works for all browsers.

I wrote a javascript function. demo: http://jsbin.com/muhipoye/1/

function clearInputFile(f){
    if(f.value){
        try{
            f.value = ''; //for IE11, latest Chrome/Firefox/Opera...
        }catch(err){
        }
        if(f.value){ //for IE5 ~ IE10
            var form = document.createElement('form'), ref = f.nextSibling;
            form.appendChild(f);
            form.reset();
            ref.parentNode.insertBefore(f,ref);
        }
    }
}

Upvotes: 0

andres descalzo
andres descalzo

Reputation: 14967

For safety you can not enter data by hand or by JavaScript in an input type file.

Upvotes: 0

nickf
nickf

Reputation: 546243

As a security measure, reading or setting the value of a file input field is not allowed. However, if you call form.reset() that will clear it out for you.

You could even loop through all the other inputs, remember their value, reset the form and then refill the other inputs, so only the files are cleared.

Upvotes: 3

Related Questions