Allow to type / enter only numbers in input textbox - Javascript

How to allow to enter only the number values into input textbox or textarea by using javascript ?
posted on 26.01.2020 at 16:41
0pnshow more
StorStor
To allow to type only numbers into input textbox by using javascript, You can use following solutions below.


This one is using the keycode method. It allows to type numbers, backspace, but also other characters, that are assigned to the number keys, for example !"£$%^&*().


<script type="text/javascript">

function keyPressed(){
var key = event.keyCode || event.charCode || event.which ;
return key;
}

</script>

<input type="text" onKeyDown="javascript: var keycode = keyPressed(event); if( (keycode<48 || keycode>57) && (keycode<96 || keycode>105) && keycode!=8 ){ return false; }" />



This one is using the regex method. It checks entered values and according to regular expression patter it will strip every non-number character.


<input type="text" id="textbox" onKeyUp="javascript: var value = document.getElementById('textbox').value; var updatedvalue = value.replace(/[^0-9]/g,''); document.getElementById('textbox').value=updatedvalue; " />

posted on 01.02.2020 at 16:27
0pnshow more
TimTim
share on facebookshare on twitter
2020 AnswerTabsTermsContact us
This site uses cookies to improve your experience, for analytics and ads. By continuing to browse this site you agree to our use of cookies.