-
자바스크립트 (JavaScript) See the Pen 자바스크립트 Input type File 파일명, 확장자만 나오게 커스텀 by kimyangsun (@kimyangsun) on CodePen.
자바스크립트 Input type File 파일명, 확장자만 나오게 커스텀한 코드 예제입니다.
파일 업로드를 누르면 파일을 첨부하는 창이 뜨고 파일을 선택하고 업로드시 파일명과 확장자까지만 표시되도록 작업한 코드입니다.
일반적인 input type="file"은 현재 파일의 경로까지 쭉 보여지는데 때에 따라서 파일명과 확장자만 표시되도록 하고 싶을때 사용하면 될 것 같습니다. :)
▶HTML
<div class="filebox"> <input class="upload-name" type="text" readonly> <input type="file" id="file_01" class="file" title="파일 업로드"> <label for="file_01" class="upload-button">파일업로드</label> </div>
▶CSS
input { -webkit-border-radius: 0; border-radius: 0; -webkit-appearance: none; -moz-appearance: none; appearance: none; border: 0; background-color: transparent; } .filebox { display: flex; gap: 10px; } .filebox input { border: 1px solid #dbdbdb; background-color: #fff; font-size: 16px; } .filebox .upload-name { max-width: 500px; width: 100%; height: 36px; padding: 4.5px 15px; pointer-events: none; } .filebox .file { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; border: 0; white-space: nowrap; clip: rect(0, 0, 0, 0); } .filebox .file:focus+label { background-color: #000; color: #fff; } .filebox .upload-button { display: inline-flex; align-items: center; justify-content: center; flex-shrink: 0; padding: 4.5px 15px; border: 1px solid #000; color: #000; cursor: pointer; line-height: 1; transition: all 0.3s; } .filebox .upload-button:hover, .filebox .upload-button:focus { background-color: #000; color: #fff; }
▶Javascript
// Input File 파일명, 확장자만 나오게 커스텀 let fileInput = document.querySelector('.filebox .file'); let nameInput = document.querySelector('.filebox .upload-name'); fileInput.addEventListener('change', function(e){ const input = e.target.closest('.file'); if (!input) return; let fileName = input.value.split('/').pop().split('\\').pop(); nameInput.value = fileName; }); // 제이쿼리를 이용해서 작업시 코드 // $(".filebox .file").on('change',function(){ // var fileName = $(this).val().split('/').pop().split('\\').pop(); // $(".upload-name").val(fileName); // });
'코딩 기록 > 코딩 소스 [HTML & CSS & JS]' 카테고리의 다른 글
(자바스크립트) input type text 휴대전화 번호 양식, 날짜 양식에 맞게 입력되는 텍스트 입력창 기능 (0) 2023.08.07 바닐라 자바스크립트 header gnb 탑메뉴 예제 3개 (PC & 모바일) (1) 2023.05.02 자바스크립트 제이쿼리 셀렉트 박스 드롭다운 기능 (Javascript Selectbox Dropdown) (0) 2023.02.16 자바스크립트 제이쿼리 header gnb 탑메뉴 예제 3 (PC & 모바일) (1) 2023.02.01 자바스크립트 제이쿼리 header gnb 탑메뉴 예제 2 (PC & 모바일) (0) 2023.01.28 댓글