Is there a quick way to set an HTML text input () to only allow numeric keystrokes (plus \'.\')?
HTML5 supports regexes, so you could use this:
<input id="numbersOnly" pattern="[0-9.]+" type="text">
Warning: Some browsers don't support this yet.
I've searched long and hard for a good answer to this, and we desperately need <input type="number"
, but short of that, these 2 are the most concise ways I could come up with:
<input type="text"
onkeyup="this.value=this.value.replace(/[^\d]/,'')">
If you dislike the non-accepted character showing for a split-second before being erased, the method below is my solution. Note the numerous additional conditions, this is to avoid disabling all sorts of navigation and hotkeys. If anyone knows how to compactify this, let us know!
<input type="text"
onkeydown="return ( event.ctrlKey || event.altKey
|| (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
|| (95<event.keyCode && event.keyCode<106)
|| (event.keyCode==8) || (event.keyCode==9)
|| (event.keyCode>34 && event.keyCode<40)
|| (event.keyCode==46) )">
input type="number"
is an HTML5 attribute.
In the other case this will help you:
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<input type="number" name="somecode" onkeypress="return isNumberKey(event)"/>
You can also compare input value (which is treated as string by default) to itself forced as numeric, like:
if(event.target.value == event.target.value * 1) {
// returns true if input value is numeric string
}
However, you need to bind that to event like keyup etc.
And one more example, which works great for me:
function validateNumber(event) {
var key = window.event ? event.keyCode : event.which;
if (event.keyCode === 8 || event.keyCode === 46) {
return true;
} else if ( key < 48 || key > 57 ) {
return false;
} else {
return true;
}
};
Also attach to keypress event
$(document).ready(function(){
$('[id^=edit]').keypress(validateNumber);
});
And HTML:
<input type="input" id="edit1" value="0" size="5" maxlength="5" />
Here is a jsFiddle example
I opted to use a combination of the two answers mentioned here i.e.
<input type="number" />
and
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
return !(charCode > 31 && (charCode < 48 || charCode > 57));
}
<input type="text" onkeypress="return isNumberKey(event);">