Question

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...

Was it helpful?

Solution

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

OTHER TIPS

See this DEMO if you want to accept numbers with fractional part (3.14 for example)

Number: <input type="number" oninput="updateNum(this)" />

function updateNum(e) {
if (isNaN(e.value)) {
    e.value = e.value.replace(/[^\d]/g,'');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top