I need to have a textbox, where, whenever typed inside should ONLY allow numbers [0-9]. I\'ve used type=\"number\"
which definitely holds the client side valida
input type="number" for getting Numeric Keyboard on Mobile Device
Java-Script
function numbersonly(myfield, e)
{
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
// control keys
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
return true;
// numbers
else if ((("0123456789").indexOf(keychar) > -1))
return true;
// only one decimal point
else if ((keychar == "."))
{
if (myfield.value.indexOf(keychar) > -1)
return false;
}
else
return false;
}
Html
<input type="number" onkeypress="return numbersonly(this, event)"/>
You can use jquery.numeric plugin.
See here similar question.
$(document).ready(function(){
$(".numeric").numeric();
});
If you don't mind using a bit of Javascript, this might help JS-BIN Demo:
<input type="number" onkeyup="if(!this.checkValidity()){this.value='';alert('Please enter a number')};"/>
Try this
define javascript function
function for allowed number with decimal as below
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
function for allowed only number not decimal is as below
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if ((charCode < 48 || charCode > 57))
return false;
return true;
}
Html
<input type="number" id="txt_number" maxlength="70" name="txt_name" placeholder="Number" onkeypress="return isNumberKey(event)">
I notice that the question was posted around 2013. Anyways, now type="number" is restricting alphabets and special characters other that 'e','.' and '+' as 'e' and '.' are considered for exponential numbers like 1.2e+12, '.' is considered for decimal numbers.
just add - min="0" max="9" onkeydown="return false;"
<input type="number" id="txt_number" maxlength="70" name="txt_name" placeholder="Number" min="0" max="9" onkeydown="return false;">