I don't know the reason of such a behavior. What I've done to solve such a problem is that, I will clear the contents of the input
each time a key is pressed.
I've added the below given line to your Script which will reset the input
each time a key is pressed.
document.getElementById("iid").value = "";
Please see the Snippet below
function test_fn(test_value){
var test_value = test_value.replace(/[^0-9]+/g, "");
document.getElementById("iid").value = "";
document.getElementById("iid").value = test_value;
}
<input name="test" id="iid" onKeyUp="test_fn(this.value)" type="number">
UPDATE
As @AssafiCohen-Arazi mentioned in his comment, this answer will prove to be incorrect if someone keeps on pressing the .
key for so long. Thus, the better solution would be the one that is mentioned in @James answer above.
UPDATE 2
Found out the reason why you were getting in-stable results. It was all because your input
type was number. You can just change your input
type to text
and your code will run perfectly.
See this fiddle
See the snippet below
function test_fn(test_value){
var test_value = test_value.replace(/[^0-9]/g, "");
document.getElementById("iid").value = test_value;
}
<input name="test" id="iid" onKeyUp="test_fn(this.value)" type="text">