How to remove a point using javascript replacement in input type number?

How to remove a point using javascript replacement in input type number?

When I tried to fill 999.in the entrance. Why doesn’t he delete the point .How can I do this?

<input name="test" id="iid" onKeyUp="test_fn(this.value)" type="number">

<script>
function test_fn(test_value){
	var test_value = test_value.replace(/[^0-9]+/g, "");
	document.getElementById("iid").value = test_value;
}
</script>
Run codeHide result
+4
source share
5 answers

See fiddle

I do not know the reasons for this behavior. What I did to solve such a problem is that I clear the contents inputevery time I press a key.

I added the line below to your Script, which will reset inputevery time you press a key.

    document.getElementById("iid").value = "";

See 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">
Run codeHide result

UPDATE

-, , - . . , , @James answer .

2

, . , input . input text, .

fiddle

.

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">
Hide result
+1

, . :

document.getElementById('iid').addEventListener('keypress', test_fn);

function test_fn(e){
  if (e.charCode == 46) e.preventDefault(); // not allowed to type .
}
<input name="test" id="iid" type="number">
Hide result
+2

, :

function test_fn(e){
    var charCode = e.which || e.keyCode;
 if (charCode >= 48 && charCode <= 57 || charCode >= 96 && charCode <= 105) return true;
    e.preventDefault();
}
<input name="test" id="iid" onKeyDown="test_fn(event)" type="number">
Hide result
0

<input name="test" id="iid" onKeyUp="test_fn(this.value)" type="text">

<script>
function test_fn(test_value){
	var test_value = test_value.replace(/[^0-9]+/g, "");
	document.getElementById("iid").value = test_value;
}
</script>
Hide result
0

In the input field type=number, the value disinfection algorithm is launched , so you cannot get the actual value from the input field if it is not a valid floating point number.

You can get around this with a type text(since you are already checking for numerical values ​​with the regulare expression/[^0-9]+/g

<input name="test" id="iid" onKeyUp="test_fn(this.value)" type="text">

<script>
  function test_fn(test_value) {
    var test_value = test_value.replace(/[^0-9]+/g, "");
    document.getElementById("iid").value = test_value;
  }
</script>
Run codeHide result

See also: How to get the original value in the field?

0
source

Source: https://habr.com/ru/post/1684039/


All Articles