2

I'm using the following function to remove non-digit characters from input fields onkeyup (as posted in numerous places). The function works fine for text inputs but when linked to a number input, the number input is completely erased when a non-digit character is typed.

Thoughts?

function RemoveNonNumeric(e)
{
    var el = e.target;

    el.value = el.value.replace(/\D/g,"");

    return;
}//end RemoveNonNumeric
cookie monster
  • 10,671
  • 4
  • 31
  • 45

2 Answers2

1

What happens is as soon as there is a non-numeric character in a number input field... the value becomes empty. One way to solve this would be to save the last true numeric value and replace the current value with that if it becomes an empty value. Seems kind of hacky, but see if it works for you:

JSFiddle

var lastNumericValue = 0;
function RemoveNonNumeric(e)
{
    if(e.keyCode === 8)
        return;
    var el = e.target;
    if(el.value === "") {
        el.value = lastNumericValue;
    } else {
        lastNumericValue = el.value;
    }
}

on second thought... how about preventing the non-numeric values from ever being placed instead of removing them after the fact? Run the following onkeypress

JSFiddle

function RemoveNonNumeric(e) {
    if (e.which < 48 || e.which > 57) {
        e.preventDefault();
    }
};
Smern
  • 18,746
  • 21
  • 72
  • 90
0

If you debug, you will find that when the value of a number input is invalid, el.value returns an empty string. I am unaware of a workaround.

James Montagne
  • 77,516
  • 14
  • 110
  • 130