-
입력창에서 숫자만 입력 가능하게 하기프론트엔드/컴포넌트 2023. 8. 24. 12:49728x90
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>무한 슬라이드</title> <link rel="stylesheet" href="style.css"> </head> <body> <input type="text" placeholder="숫자만 입력해주세요!"> <script src="app.js"></script> </body> </html>
body{ margin: 0; padding: 100px; text-align: center; } input{ width: 20rem; height: 5rem; outline: none; border: none; border-bottom: 2px solid #eee; font-size: 2rem; color: #ccc; } input::placeholder{ font-size: 2rem; }
const input = document.querySelector('input') input.addEventListener('keyup', function(e){ if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) { // 0-9 only console.log('숫자입니다') }else{ console.log('숫자가 아닙니다.') console.log(this.value.slice(0, this.value.length-1)) this.value = this.value.split('').filter(c => { console.log(parseInt(c) == c) return parseInt(c) == c }).join('') console.log(this.value) } })
숫자가 아닌 경우 입력창 글자를 하나씩 가져와서 parseInt 로 변경한다. 숫자인 경우에는 자료형은 다르지만 값은 같기 때문에 == 연산자를 사용하면 만족한다. 하지만 숫자가 아닌 글자는 parseInt 로 변경한 값이 NaN(Not a Number)가 되기 때문에 원래 값이랑 다르다. 그러므로 숫자만 걸러진다.
728x90'프론트엔드 > 컴포넌트' 카테고리의 다른 글
위로 증가하는 바 그래프 (0) 2024.02.16 돋보기 효과 (0) 2024.02.14 말풍선 툴팁 & 드롭다운 메뉴 만들기 (0) 2023.07.29 부드러운 가로 스크롤링 (3) - ease 함수 사용 (0) 2023.07.06 로딩 애니메이션 (0) 2023.07.05