Grow your CSS skills. Land your dream job.

Last updated on:

Clear a File Input

You can just clone it and replace it with itself, with all events still attached.

var input = $("#control");

function something_happens() {
    input.replaceWith(input.val('').clone(true));
};


      
		

Comments

  1. Sreekanth
    Permalink to comment#

    Click on Clear button for more than 1 time does n’t work.

  2. Not working…

  3. Tobias
    Permalink to comment#

    Same here, the example works only the first time.
    Selecting a different file puts “changed” to the console.log but clicking on the “clear” link does nothing.
    Win7/Chrome 26

  4. nicolas
    Permalink to comment#

    not working

  5. dibiler
    Permalink to comment#

    I believe that it’s not working,because variable “controlBn” is assigned only once (the first time equals $(‘#control’). And as that element is being replaced with a new clone of it, the var “controlBn” may be pointing to an inexistent element after that.
    I would put just :
    $('#clear').on('click' ,function(){
    $('#control').replaceWith( $('#control').val('').clone( true ) );
    });

    rather than the code above
    (just a guess)

  6. niwtsew
    Permalink to comment#

    Though .val(”) works for FF, but it does not work for IE.

  7. Permalink to comment#

    Thank you. Just what I needed. Works perfectly ;)

  8. Permalink to comment#

    @dibiler’s solution works great. The control variable has to be reinitialized inside the click callback function.

    clearBn.on("click", function(){
        var control = $("#control");
        control.replaceWith( control.val('').clone( true ) );
    });
    

    A working demo is available here – http://jsfiddle.net/jesin/FEKrz/

  9. Pablo
    Permalink to comment#

    Amazing!

  10. Awesomeness!

  11. ETorres
    Permalink to comment#

    Hey … it’s great! but not work to FILE type :-(

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like ```this```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".