program story

JavaScript로 HTML 파일 입력을 지우려면 어떻게해야합니까?

inputbox 2020. 7. 24. 20:51
반응형

JavaScript로 HTML 파일 입력을 지우려면 어떻게해야합니까?


양식에서 파일 입력을 지우고 싶습니다.

소스를 동일한 방법으로 설정하는 방법에 대해 알고 있지만 ...이 방법으로 선택한 파일 경로를 지우지 않습니다.

참고 : 페이지를 다시로드하거나 양식을 재설정하거나 AJAX 호출을 수행하지 않으려 고합니다.

이게 가능해?


해당 노드를 제거하고 동일한 이름으로 새 노드를 작성하는 것은 어떻습니까?


자바 스크립트로 파일 입력을 지우는 방법에는 3 가지가 있습니다.

  1. 값 특성을 비어 있거나 널로 설정하십시오.

    IE11 + 및 기타 최신 브라우저에서 작동합니다.

  2. 새 파일 입력 요소를 작성하고 이전 파일 입력 요소를 바꾸십시오.

    단점은 이벤트 리스너와 expando 속성이 손실된다는 것입니다.

  3. form.reset () 메소드를 통해 소유자 양식을 재설정하십시오.

    동일한 소유자 양식의 다른 입력 요소에 영향을주지 않기 위해 비어있는 새 양식을 작성하고 파일 입력 요소를이 새 양식에 추가하고 재설정 할 수 있습니다. 이 방법은 모든 브라우저에서 작동합니다.

자바 스크립트 함수를 작성했습니다. 데모 : 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'),
                parentNode = f.parentNode, ref = f.nextSibling;
            form.appendChild(f);
            form.reset();
            parentNode.insertBefore(f,ref);
        }
    }
}

tl; dr : 최신 브라우저의 경우

input.value = '';

이전 답변 :

어때요?

input.type = "text";
input.type = "file";

왜 이것이 웹킷에서 작동 하지 않는지 이해해야 합니다.

어쨌든 이것은 IE9>, Firefox 및 Opera에서 작동합니다.
웹킷의 상황은 파일로 다시 변경할 수없는 것 같습니다.
IE8에서는 보안 예외가 발생합니다.

편집 : 웹 키트, Opera 및 firefox의 경우 다음과 같이 작동합니다.

input.value = '';

(이 제안으로 위의 답변을 확인하십시오)

GC 없이도이 크로스 브라우저를 수행하는 더 깔끔한 방법을 찾을 수 있는지 살펴 보겠습니다.

편집 2 :

try{
    inputs[i].value = '';
    if(inputs[i].value){
        inputs[i].type = "text";
        inputs[i].type = "file";
    }
}catch(e){}

대부분의 브라우저에서 작동합니다. IE <9에서는 작동하지 않습니다.
파이어 폭스 20, 크롬 24, 오페라 12, IE7, IE8, IE9 및 IE10에서 테스트되었습니다.


불행히도 위의 답변 중 어느 것도 모든 기초를 다루는 것으로 보이지 않습니다. 적어도 바닐라 자바 ​​스크립트로 테스트하지 않았습니다.

  • .value = null파이어 폭스, 쵸메, 오페라와 IE11에 작업에 나타납니다 (하지만 하지 IE8 / 10분의 9)

  • .cloneNode.clone()FireFox에서 (및 jQuery에서) .value오버 를 복사하는 것처럼 보이 므로 복제본이 무의미합니다.

FireFox (27 및 28), Chrome (33), IE (8, 9, 10, 11), Opera (17)에서 작동하는 바닐라 자바 ​​스크립트 기능은 다음과 같습니다. 이것은 현재 사용 가능한 유일한 브라우저입니다 테스트 할 나에게.

function clearFileInput(ctrl) {
  try {
    ctrl.value = null;
  } catch(ex) { }
  if (ctrl.value) {
    ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
  }
}

The ctrl parameter is the file input itself, so the function would be called as...

clearFileInput(document.getElementById("myFileInput"));

Setting the value to '' does not work in all browsers.

Instead try setting the value to null like so:

document.getElementById('your_input_id').value= null;

EDIT: I get the very valid security reasons for not allowing JS to set the file input, however it does seem reasonable to provide a simple mechanism for clearing already selecting output. I tried using an empty string but it did not work in all browsers, NULL worked in all the browsers I tried (Opera, Chrome, FF, IE11+ and Safari).

EDIT: Please note that setting to NULL works on all browsers while setting to an empty string did not.


U need replace it with new file input. Here is how it can be done with jQuery:

var inputFile = $('input[type=field]');
inputFile.wrap('<div />');

and use this line when you need to clear input field (on some event for example):

inputFile.parent().html( inputFile.parent().html() );

SOLUTION

The following code worked for me with jQuery. It works in every browser and allows to preserve events and custom properties.

var $el = $('#your-input-id');
$el.wrap('<form>').closest('form').get(0).reset();
$el.unwrap();

DEMO

See this jsFiddle for code and demonstration.

LINKS


document.getElementById('your_input_id').value=''

Edit:
This one doesn't work in IE and opera, but seems to work for firefox, safari and chrome.


I was having same problem and i came up with this.

var file = document.querySelector('input');
var emptyFile = document.createElement('input');
emptyFile.type = 'file';

document.querySelector('button').onclick = function(){
  file.files = emptyFile.files;
}
<input type='file'>
<button>clear</button>


The above answers offer somewhat clumsy solutions for the following reasons:

  1. I don't like having to wrap the input first and then getting the html, it is very involved and dirty.

  2. Cross browser JS is handy and it seems that in this case there are too many unknowns to reliably use type switching (which, again, is a bit dirty) and setting value to ''

So I offer you my jQuery based solution:

$('#myinput').replaceWith($('#myinput').clone())

It does what it says, it replaces the input with a clone of itself. The clone won't have the file selected.

Advantages:

  1. Simple and understandable code
  2. No clumsy wrapping or type switching
  3. Cross browser compatibility (correct me if I am wrong here)

Result: Happy programmer


That's actually quite easy.

document.querySelector('#input-field').value = '';

I have been looking for simple and clean way to clear HTML file input, the above answers are great, but none of them really answers what i'm looking for, until i came across on the web with simple an elegant way to do it :

var $input = $("#control");

$input.replaceWith($input.val('').clone(true));

all the credit goes to Chris Coyier.

// Referneces
var control = $("#control"),
    clearBn = $("#clear");

// Setup the clear functionality
clearBn.on("click", function(){
    control.replaceWith( control.val('').clone( true ) );
});

// Some bound handlers to preserve when cloning
control.on({
    change: function(){ console.log( "Changed" ) },
     focus: function(){ console.log(  "Focus"  ) }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="file" id="control">
<br><br>
<a href="#" id="clear">Clear</a>


What helped me is, I tried to fetch and upload the last selected file using a loop, instead of clearing out the queue, and it worked. Here is the code.

for (int i = 0; i <= Request.Files.Count-1; i++)
{
 HttpPostedFileBase uploadfile = files[i];
 Stream fs = uploadfile.InputStream;
 BinaryReader br = new BinaryReader(fs);
 Byte[] imageBytes = br.ReadBytes((Int32)fs.Length);
}

Hope this might help some.


I tried most of solutions but did not seem anyone to work. However I found a walk around for it below.

The structure of the form is: form => label, input and submit button. After we choose a file, the filename will be shown by the label by doing so manually in JavaScript.

So my strategy is: initially the submit button is disabled, after a file is chosen, the submit button disabled attribute will be removed such that I can submit file. After I submit, I clear the label which makes it look like I clear the file input but actually not. Then I will disable the submit button again to prevent from submitting the form.

By setting the submit button disable or not, I stop the file from submitted many times unless I choose another file.

참고URL : https://stackoverflow.com/questions/1703228/how-can-i-clear-an-html-file-input-with-javascript

반응형