0

I need to validate a textbox which can only takes numbers. So i'm using the code below. It passes a message to the user but it also writes the alphabet to the textbox. I don't want anything written when user enters an alphabet.

<script type="text/javascript">
function numeralsOnly(evt) {
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : 
        ((evt.which) ? evt.which : 0));
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        alert("This field can only contain numbers.");
        return false;
    }
    return true;
}
</script>
Sumurai8
  • 20,333
  • 11
  • 66
  • 100
v0ld3m0rt
  • 866
  • 3
  • 12
  • 47
  • 1
    possible duplicate of [Validate numbers in JavaScript - IsNumeric()](http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric) – CloudyMarble Sep 10 '13 at 04:59

2 Answers2

3

You can use HTML5 input type number to restrict only numbers:

<input type="number" name="someid" />

or

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

<input type="someid" name="number" onkeypress="return isNumberKey(event)"/>

DEMO FIDDLE

Kiran
  • 20,167
  • 11
  • 67
  • 99
  • i don't have HTML5. I want to alter the above coding to match the requirement. Now what? – v0ld3m0rt Sep 10 '13 at 05:05
  • I mentioned both ways hmtl5 and normal javascript code you can use anyone. – Kiran Sep 10 '13 at 05:06
  • Did you add `onkeypress="return isNumberKey(event)"` to your HTML input tag like @Unknown mentioned? In your case, `onkeypress="return numeralsOnly(event)"`. – cbayram Sep 10 '13 at 05:11
  • Yeah, its working there but not on my system. And yes I've called the function. – v0ld3m0rt Sep 10 '13 at 05:18
  • Make sure that you are calling same function that you mentioned in html and check whether function is invoked onkeypress. – Kiran Sep 10 '13 at 05:20
1

you use HTML5 's input type = number

<input type="number" max="100" min="1" steps="any"/>

There is javascript plugin availble JqueryAlphanumeric

$("#MytextBoxId").numeric(); // this will allow user to enter numbers only.
sudhansu63
  • 6,025
  • 4
  • 39
  • 52