You Can Still Type Non-Numbers In A Type Number HTML Input

We can set the type property of an HTML input to number to accept only numbers. But we can still type in something like 00001213400012 or 1-5-5-5--442-, which are not quite what I usually define as normal numbers.

By the way, I wrote that input values are treated as type string even if the type of the input is set to be number.

Try type in 000123 or 1-2-53 in this input which is set to be type number.


Type:
Input:

Using Number or parseFolat

We can use parseFloat() or Number() method to convert the type of input values from string to number, now try to type in 000123 or 1-2-352.

Type:
Input:
<input oninput="show(this)" type="number" /><br />
<div>Type: <span id="showType"></span></div>
<div>Input: <span id="showNo"></span></div>
<script>
  function show(t){
	var value = Number(t.value);//or parseFloat(t.value);
    	showType.innerHTML = typeof(value);
    	showNo.innerHTML = value;
  };
</script>

Still Problematic

Although what we type in the input is convert to number. 000123 is converted to 123, while 1-2-352 is converted to 0. But, both 000123 and 1-2-352 are still preserved in the input box. They show in the input box. And when we want to type in something else, we need to delete them first. We want input to be clean nad clear of non-numbers.
One thing to notice is that when we use parseFloat(), 1-2-352 has type NaN.

Solution

We need to rewrite what is in the input box by adding this code t.value = Number(t.value).

Type:
Input:
<input onkeyup="show_2(this)" type="number" /><br />
<div>Type: <span id="showType_2"></span></div>
<div>Input: <span id="showNo_2"></span></div>
<script>
 function show_2(t){
    t.value = parseFloat(t.value);//or Number(t.value);
	var value = parseFloat(t.value);//or Number(t.value);
    	showType_2.innerHTML = typeof(value);
    	showNo_2.innerHTML = value;
   };
</script>
Notice how I use onkeyup, not oninput, here as the event listener for this input. Becsue oninput will prohibit users to type in any megative numbers, since the negative sign(-) is "Not a Number".

Another Code, Maybe Better


<input onkeyup="this.value = parseFloat(this.value)" type="number" /><br />

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser