Skip to content

Instantly share code, notes, and snippets.

@afrontend
Created October 30, 2020 15:45
Show Gist options
  • Save afrontend/a6c2715297df5c9a2ad7638b1e0a1eeb to your computer and use it in GitHub Desktop.
Save afrontend/a6c2715297df5c9a2ad7638b1e0a1eeb to your computer and use it in GitHub Desktop.
<INPUT> 에서 숫자만 입력 받는 방법
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<style type="text/css">
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
text-align: center;
margin-top: 60px;
}
</style>
</head>
<body>
<div id="app">
<input placeholder="Enter some text"/>
</div>
<script>
const input = document.querySelector('input')
const onlyNumber = (function(){
let prevValue = ''
return function (e) {
const value = e.target.value
if (/^[0-9]*$/.test(value)) {
prevValue = value
e.target.value = value
} else {
e.target.value = prevValue
}
}
})()
input.addEventListener('input', onlyNumber)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment