0

I have a function:-

function resetInputFile(elem) {
    elem.wrap('<form>').closest('form').get(0).reset();
    elem.unwrap();
}

I call the function like this:-

resetInputFile(document.queryElement('#image'));

How can I convert the LOCs

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

into pure javascript?

I want to implement the logic in ReactJS, but I don't want to use jquery with ReactJS. So I need to do it with pure javascript.

3
  • Do you have to do it this way or you just want to reset the file input ? You could just reset it with document.getElementById("myFile").value = ""; Commented Dec 26, 2023 at 6:20
  • @OmarAtri document.getElementById("myFile").value = "" doesn't clear the previously selected file from the file input. I had tested it before and that's why I chose wrap() and unwrap() method previously in another PHP project where I could use JQuery. Commented Dec 26, 2023 at 6:23
  • 1
    Does this answer your question? How can I clear an HTML file input with JavaScript? Commented Dec 26, 2023 at 6:30

2 Answers 2

2

You can try something like:

function resetInputFile(elem) {
  const form = document.createElement('form');
  const parent = elem.parentNode;

  parent.insertBefore(form, elem);
  form.appendChild(elem);
  form.reset();
  parent.insertBefore(elem, form);
  parent.removeChild(form);
}

function resetFileInput() {
  resetInputFile(document.querySelector('#image'));
}
<input type="file" id="image">
<button onclick="resetFileInput()">Reset File Input</button>

Sign up to request clarification or add additional context in comments.

Comments

1

function resetInputFile() {
  const elem = document.getElementById('image'); //--Get the input element

  const form = document.createElement('form'); //--> Create a <form> element
  const parent = elem.parentNode;//-- Get the parent node of elem

  //-->Replace elem with the newly created form, moving elem inside the form
  parent.replaceChild(form, elem);
  form.appendChild(elem);

  //--Reset the form
  if (form && form.parentNode) {
    form.reset();
    // Restore elem to its original position outside the form
    form.parentNode.replaceChild(elem, form);
  }

  // Unwrap the element
  if (elem.parentNode) {
    const grandParent = elem.parentNode.parentNode; //--> Get the grandparent node
    grandParent.replaceChild(elem, elem.parentNode); //--->Replace form with elem
  }
}
<input type="file" id="image" />
 <button onclick="resetInputFile()">Reset Input File</button>

Comments

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.