Format Number in an Html5 Input Tag
This Is My Input Is It Possible to Only Allow Users to Enter Numbers That Match the Pattern '0.00', Like the Way I Declare It in the Step Attribute, Without...
This is my input
<input type="number" id="inputNumbers" step="0.01" ></input>
Is it possible to only allow users to enter numbers that match the pattern '0.00', like the way I declare it in the step attribute, without using JavaScript?
Example: If the user types '1.23' and then tries to enter a new number, decimal or comma it can't and the number stays at '1.23'.
If there's not a way to match the step attribute, Is it possible to only allow one decimal in the number?
3 Answers
It can be achieved using javascript with corner case handling using toLocaleString()
function getChange(){
// 48 - 57 (0-9)
var str1 = valueRef.value;
if((str1[str1.length-1]).charCodeAt() < 48 || (str1[str1.length-1]).charCodeAt() > 57){
valueRef.value = str1.substring(0,str1.length-1 );
return;
}
// t.replace(/,/g,'')
let str = (valueRef.value).replace(/,/g,'');
let value = +str;
valueRef.value = value.toLocaleString();
}
function inputLimiter(e,allow) {
var AllowableCharacters = '';
if (allow == 'custom'){AllowableCharacters=' 1234567890.';}
var k = document.all?parseInt(e.keyCode): parseInt(e.which);
if (k!=13 && k!=8 && k!=0){
if ((e.ctrlKey==false) && (e.altKey==false)) {
return (AllowableCharacters.indexOf(String.fromCharCode(k))!=-1);
} else {
return true;
}
} else {
return true;
}
}
<script src=""></script>
<script src=""></script>
<input type="text" id="NameCharacters" onkeypress="return inputLimiter(event,'custom')" value="" maxlength="4" /></p>
In Javascript. But this was as far as I got, will just leave this here for awhile, need to handle other stuffs.