• Q&A
  • 회원가입
  • 로그인

[js] JS - 숫자만입력

474  

방법1 

 

<input type="number" onkeyup="num(this)">

 

<script>

function num(obj) {

    obj.value = obj.value.replace(/\D/g, '');

}

</script>

 

결과보기

슈와이 님 (181219) https://sir.kr/qa/281599

 

 

방법2

 

<script type="text/javascript">

function onlyNumber(event){

    event = event || window.event;

    var keyID = (event.which) ? event.which : event.keyCode;

    if ( (keyID >= 48 && keyID <= 57) || (keyID >= 96 && keyID <= 105) || keyID == 8 || keyID == 46 || keyID == 37 || keyID == 39 ) 

        return;

    else

        return false;

}

function removeChar(event) {

    event = event || window.event;

    var keyID = (event.which) ? event.which : event.keyCode;

    if ( keyID == 8 || keyID == 46 || keyID == 37 || keyID == 39 ) 

        return;

    else

        event.target.value = event.target.value.replace(/[^0-9]/g, "");

}

</script>


<input type="number" pattern="[0-9]*" placeholder="숫자만 입력"  onkeydown="return onlyNumber(event)" onkeyup="removeChar(event)" style="ime-mode:disabled;">

 

결과보기

웹스킬 님 http://webskills.kr/archives/310



찾아주셔서 감사합니다. Since 2012