programing

파일 입력을 지우는 방법

copyandpastes 2023. 8. 14. 23:29
반응형

파일 입력을 지우는 방법

아래는 파일 입력과 "파일 지우기" 버튼을 표시하는 jquery 코드의 일부입니다.

var $imagefile = $('<input />').attr({
    type: 'file',
    name: 'imageFile',
    class: 'imageFile'
});

$image.append($imagefile);

var $imageclear = $('<input />').attr({
    type: 'button',
    name: 'imageClear',
    class: 'imageClear',
    value: 'Clear File'
});

$image.append($imageclear);

이제 "파일 지우기" 단추가 있는 이유는 단추를 클릭하면 파일 입력에 있는 모든 항목이 지워지기 때문입니다.파일 지우기 단추를 클릭할 때 실제로 파일 입력이 지워지도록 코딩하려면 어떻게 해야 합니까?

이렇게 하면 됩니다.

$imageClear.on('click', function() { 
    $imageFile.val(''); 
});

jQuery를 사용하여 파일 입력 지우기

$("#fileInputId").val(null);

JavaScript로 파일 입력 지우기

document.getElementById("fileInputId").value = null;

React 사용자의 경우

e.target.value = ""

그러나 파일 입력 요소가 다른 요소에 의해 트리거된 경우(사용자가 포함된 경우)htmlFor속성) - 그것은 당신이 이벤트를 가지고 있지 않다는 것을 의미합니다.

그래서 당신은 심판을 사용할 수 있습니다.

func 시작 시:

const inputRef = React.useRef();

입력 요소에

<input type="file" ref={inputRef} />

그런 다음 onClick 기능(예를 들어)에서 다음과 같이 쓸 수 있습니다.

inputRef.current.value = "" 
  • 반응 클래스 - 동일한 아이디어이지만 생성자의 차이:this.inputRef = React.createRef()

이것도 제가 사용하고 싶은 방법이지만 모든 이벤트가 새 개체와 연결된 상태로 유지되고 내용을 지우려면 clone 메서드에 bool true 매개 변수를 추가해야 한다고 생각합니다.

    var input = $("#fileInput");

    function clearInput() {
        input = input.val('').clone(true);
    };

https://api.jquery.com/clone/

설정별$("ID").val(null)나를 위해 일했습니다.

아래와 같이 입력 ID를 가져오고 put val이 비어 있습니다.참고: val 빈 큰따옴표 val(" ") 사이에 공백을 넣지 마십시오.

 $('#imageFileId').val("")

이 코드는 모든 브라우저와 모든 입력에 대해 작동합니다.

$('#your_target_input').attr('value', '');

크로스 브라우저 기능을 사용하려면 태그를 제거한 다음() append() 또는 prepend()를 추가하거나 다른 방식으로 동일한 특성을 가진 입력 태그의 새 인스턴스를 다시 추가합니다.

<form method="POST" enctype="multipart/form-data">
<label for="fileinput">
 <input type="file" name="fileinput" id="fileinput" />
</label>
</form>

$("#fileinput").remove();
$("<input>")
  .attr({
    type: 'file',
    id: 'fileinput',
    name: 'fileinput'
    })
  .appendTo($("label[for='fileinput']"));

이 작업은 다음 작업에 사용됩니다.

 $("#yourINPUTfile").val("");

이것은 당신의 문제를 해결할 수 있습니다, 저는 엑센트가 있는 아카이브를 이름으로 전달할 때 문제가 있고, 정상과 다른 것이 있다면 아카이브의 크기와 명확한 입력을 확인하는 것을 해결했습니다.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="file" placeholder="hello world" id="input_file" />

    <script
      src="https://code.jquery.com/jquery-3.6.1.js"
      integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI="
      crossorigin="anonymous"
    ></script>
    <script>
      $("input:file").change(function () {
        var fileInput = $(this); // => Gets the file data
        var fileSize = fileInput.get(0).files[0].size; // => Value in bytes
        if (fileSize == 0) {
          $("#input_file").val("");
          console.log('Something wrong :/');
        } else {
            console.log('good thats working :D');
        }
      });
    </script>
  </body>
</html>

$('#myImage').filestyle('clear');

사용 중

  • jquery 2.2.1 &
  • jquery UI 1.11.4

나는 이런 일을 해왔고 그것은 나에게 효과가 있습니다.

$('#fileInput').val(null); 

이 경우 다른 솔루션은 이 방법 외에는 작동하지 않았습니다.

$('.bootstrap-filestyle :input').val('');

그러나 페이지에 하나 이상의 파일 입력이 있을 경우 모든 파일의 텍스트가 재설정됩니다.

좋아요, 그것은 효과가 있고 승인되었습니다.

$('.file-input-element').change();

$(document).on("change", 'input[type="file"][data-module-name="Test"]', function (e) {
    e.preventDefault();
    var controlName = $(this).attr('name');
    var fileFormData = new FormData();
    var files = e.target.files;
    if (files.length > 0) {
        var file = files[0];
        var fileName = file.name;
        var fileSize = file.size; //in bytes
        var fileType = file.type; //like "image/png"
        if (fileSize > App.maxAllowedSizeInBytes) {
            e.target.value = '';
            $(this).attr("value", '');
            $(this).change();
            toastr.error(langData.UIMaxFileSizeShouldBeFiveMb);
            return;
        } else {
            App.test.validation.ValidateFile(file);
            fileFormData.append("file", file, fileName);
            App.test.uploadFile(fileFormData, controlName, $(this));
        }
    }
});

언급URL : https://stackoverflow.com/questions/9617738/how-to-clear-file-input

반응형