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 ?
0
give a positive ratinggive a negative rating
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 pattern 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; " />

Share on FacebookShare on TwitterShare on LinkedInSend email
1 answer
x
x
2024 AnswerTabsTermsContact us