programing tip

HTML

itbloger 2020. 7. 2. 07:59
반응형

HTML 파일 선택 이벤트


이 코드가 있다고 가정 해 봅시다.

<form action='' method='POST' enctype='multipart/form-data'>
    <input type='file' name='userFile'><br>
    <input type='submit' name='upload_btn' value='upload'>
</form>

결과는 다음과 같습니다.

찾아보기 및 업로드 버튼을 보여주는 이미지

사용자가 '찾아보기 ...'버튼을 클릭하면 파일 검색 대화 상자가 열립니다.

파일이 선택된 파일 검색 대화 상자를 보여주는 이미지

사용자는 파일을 두 번 클릭하거나 '열기'버튼을 클릭하여 파일을 선택합니다.

파일을 선택한 후 알림을받을 수있는 Javascript 이벤트가 있습니까?


변경 이벤트를 듣습니다.

input.onchange = function(e) { 
  ..
};

파일을 다시로드해야 할 때 입력 값을 지울 수 있습니다. 다음에 파일을 추가하면 '변경시'이벤트가 트리거됩니다.

document.getElementById('my_input').value = null;
// ^ that just erase the file path but do the trick

jQuery 방법 :

$('input[name=myInputName]').change(function(ev) {

    // your code
});

취소를 클릭해도 변경 이벤트가 호출됩니다.


그것이 순수한 JS로 내가 한 방식입니다.

var files = document.getElementById('filePoster');
var submit = document.getElementById('submitFiles');
var warning = document.getElementById('warning');
files.addEventListener("change", function () {
  if (files.files.length > 10) {
    submit.disabled = true;
    warning.classList += "warn"
    return;
  }
  submit.disabled = false;
});
#warning {
    text-align: center;
}

#warning.warn {
	color: red;
	transform: scale(1.5);
	transition: 1s all;
}
<section id="shortcode-5" class="shortcode-5 pb-50">
    <p id="warning">Please do not upload more than 10 images at once.</p>
    <form class="imagePoster" enctype="multipart/form-data" action="/gallery/imagePoster" method="post">
        <div class="input-group">
  	    <input id="filePoster" type="file" class="form-control" name="photo" required="required" multiple="multiple" />
	    <button id="submitFiles" class="btn btn-primary" type="submit" name="button">Submit</button>
        </div>
    </form>
</section>

참고 URL : https://stackoverflow.com/questions/3528359/html-input-type-file-file-selection-event

반응형