1

I'm trying to clear the component if the user attaches a file that is not accepted. I'm trying to do it right after it is attached. I took a look on some examples here, where some of them showed me how to do it with a reset button, that resets the whole form (something that I don't wanna do), or cloning the component (something that I tried but it is not working). I would be glad if someone could help me. Thanks in advance.

Here is an example of what I have:

$("#mycomponent").on("change", function()
{
    var extension = $(this).val().split(".").pop().toString();

    if((extension === "pdf") || (extension === "docx") || (extension === "doc"))
    {
        alert("OK");    
    }
    else
    {
        alert("File extension not accepted");

        var mycomponent = $("#mycomponent");
        mycomponent.replaceWith(mycomponent = mycomponent.clone(true));
    }
});
1
  • Why not just do a mycomponent.val(""); ? Commented Apr 26, 2017 at 13:58

2 Answers 2

4

You can clear the component with val(), like this:

$("#mycomponent").on("change", function()
{
    var extension = $(this).val().split(".").pop().toString();

    if((extension === "pdf") || (extension === "docx") || (extension === "doc"))
    {
        alert("OK");    
    }
    else
    {
        alert("File extension not accepted");

        var mycomponent = $("#mycomponent");
        mycomponent.val("");
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Funcionou desse jeito também. Valeu!
2

Working fiddle.

Using the wrap()/unwrap() functions like the following way should work :

$(this).wrap('<form>').closest('form').get(0).reset();
$(this).unwrap();

Hope this helps.

$("#mycomponent").on("change", function(){
  var extension = $(this).val().split(".").pop().toString();

  if((extension === "pdf") || (extension === "docx") || (extension === "doc"))
  {
    console.log("OK");    
  }
  else
  {
    console.log("File extension not accepted");
    
    $(this).wrap('<form>').closest('form').get(0).reset();
    $(this).unwrap();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="mycomponent" />

3 Comments

Didn't work, the component is still showing the file name attached with the wrong extension
True, I've updated my answer with working snippet, check please.
You're no longer using clone, can you edit out that part please (for the sake of people seeing this in future)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.