I have a number type input that I want to prevent people from entering anything but numbers. The examples I found work well with input type text fields but don't work well with number fields.
Works well :)
<input type="text" onkeyup="this.value=this.value.replace(/[^\d]/,'')">
Doesn't works well :(
<input type="number" onkeyup="this.value=this.value.replace(/[^\d]/,'')">
Try it for yourself on JSFiddle
Please help...
How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
The REGEXREPLACE( ) function uses a regular expression to find matching patterns in data, and replaces any matching values with a new string. standardizes spacing in character data by replacing one or more spaces between text characters with a single space.
In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate. In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.
I've just done some simple testing using JSFiddle and it would appear that if there is an invalid input on an <input type="number" />
element then the this.value
property is returned blank.
The following line showed this result when using Chrome:
<input type="number" oninput="alert(this.value)">
JSFiddle Demo
In fact here's the reason why this happens:
The value attribute, if specified and not empty, must have a value that is a valid floating-point number.
The value sanitization algorithm is as follows: If the value of the element is not a valid floating-point number, then set it to the empty string instead.
^ From the HTML5 Draft Paper section on the implementation of the number input type
This problem has taken my interest now and I've come up with a little workaround.
<input type="number" oninput="updateNum(this)">
function updateNum(e)
{
e.select();
e.value = getSelection().toString().replace(/[^\d]/g,'');
}
This has the potential to be buggy if the selection where to change between commands.
JSFiddle for the workaround
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With