I have input where user must enter the number of the with no more than 4 decimal places:
<input type="text" name="price" />
how to do that, so it is impossible to enter more than 4 digits after the decimal point?
I have input where user must enter the number of the with no more than 4 decimal places:
<input type="text" name="price" />
how to do that, so it is impossible to enter more than 4 digits after the decimal point?
There is a method for that too,
.toFixed(4); // 4 would be the number of ints after decimal point.
It would get/allow only 4 characters after the .
character.
The toFixed() method formats a number using fixed-point notation.
Further more you can learn some more from the Document I have attached to the post. They have a well explained Example of this method too.
From Mozilla Developer Network: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
In HTML5:
<input type="number" step="0.0001" />
If you want to style invalid inputs (some browsers do it by default), you can use :invalid
selector:
input:invalid { box-shadow: 0 0 1.5px 1px red; }
Note this approach won't attempt to truncate the number automagically, but if the user enters more than four decimal digits, the input will become invalid, and thus the form won't be submitted:
$("#price").on('keyup',function(){
$("#price").val($("#price").val().replace(/[^\d.-]/g, ''));
var price = parseFloat($("#price").val());
var decimals = ((price).toFixed(5)).replace(/^-?\d*\.?|0+$/g, '').length;
if(decimals >= 4)
{
$("#price").val(price.toFixed(4));
}
});
Determines the number of decimals, if it's greater than 4 it sets the value in the input back to 4.
Also doesn't allow any non-numeric characters in the input.
Error pop ups are crap UI. http://jsfiddle.net/calder12/z4f5B/3/
User toFixed:
<input type="text" name="price" onBlur="this.value = parseFloat(this.value).toFixed(4);" />
Add maxlength="4" to your input code.
<input type="text" name="price" maxlength="4" />