I have got a task to prevent keypress two digits after a decimal number. My jquery file is
$(function(){
$(\'#name\').bind(\'paste\', function(){
This might be helpful to some. I mixed the answers of this guy, @Tats_innit from https://stackoverflow.com/a/10514166/5382523 and @Rick Calder above.
EDIT also from this guy, isJustMe from https://stackoverflow.com/a/17289322 for the parseFloat with "|| 0". Because if the input's field is null or zero "NaN" is shown and you can't delete it.
HTML
JAVASCRIPT (JQUERY)
$('.price').keypress(function(event) {
if(event.which < 46 || event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46 && $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var price = parseFloat($("#txt_prod_price").val()) || 0;
$("#txt_prod_price").val(price.toFixed(2));
}
});
the "price" is pre-defined.
Note: still have buggy inputs but still kickin'. (y)
More info about toFixed - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed